0

I'm trying to pass a parameter from a number of list items to differentiate them when clicked.

class SettingsGeneral extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      form_fields: ["Select option"],
      selectedSetting: "general",
      configSettings: {}
    };

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick({ e }) {
    const { param } = e.target.dataset;
    console.log(param); // e.currentTarget.value would be equivalent
  }

  render() {
    return (
      <ul className="settings-list">
        <li data-param="value" onClick={this.handleClick}></li>
      </ul>
    );
  }
}

With the current code, I get an error:

TypeError: Cannot read property 'target' of undefined

Which means the value isn't getting sent to the handleClick function and I try log it in the console.

How do I go about doing this and what is the best way to do this? There are a lot of different answers online.

1
  • You can access event via handleClick(e) Commented Nov 24, 2019 at 20:12

3 Answers 3

1

You can do it two ways:

  1. Pass event and get the data from it's dataset:
handleClick(e) {
    const { param } = e.target.dataset;
    console.log(param); // e.currentTarget.value would be equivalent
  }

  render() {
    return (
      <ul className="settings-list">
        <li data-param="value" onClick={this.handleClick}></li>
      </ul>
    );
  }
  1. Pass the value directly to onClick handler:
handleClick(value) {
    console.log(value);
  }

  render() {
    return (
      <ul className="settings-list">
        <li onClick={() => this.handleClick(value)}></li>
      </ul>
    );
  }
Sign up to request clarification or add additional context in comments.

Comments

1

The only thing what you need to change in order to eliminate the error is the following:

handleClick(e) {
   const { param } = e.target.dataset;

   console.log(param); // e.currentTarget.value would be equivalent
}

It was wrongly destructured like {e}, it has to be e only in the parameter list of handleClick.

As the documentation states for Event.target:

The target property of the Event interface is a reference to the object that dispatched the event. It is different from Event.currentTarget when the event handler is called during the bubbling or capturing phase of the event.

If you would like to further destructure you can do the following:

handleClick({ target }) {
   const { param } = target.dataset;

   // ... further code
}

I hope this helps!

Comments

0

i think this would work

  handleClick(e) {
    const { param } = e.target.dataset;
    console.log(param);
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.