Celt67
Celt67

Reputation: 27

How to pass parameter from list item to function with onClick event

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.

Upvotes: 0

Views: 2099

Answers (3)

norbitrial
norbitrial

Reputation: 15166

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!

Upvotes: 1

Clarity
Clarity

Reputation: 10873

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>
    );
  }

Upvotes: 1

Peter Safwat
Peter Safwat

Reputation: 47

i think this would work

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

Upvotes: 0

Related Questions