Reputation: 27
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
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
Reputation: 10873
You can do it two ways:
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>
);
}
onClick
handler:handleClick(value) {
console.log(value);
}
render() {
return (
<ul className="settings-list">
<li onClick={() => this.handleClick(value)}></li>
</ul>
);
}
Upvotes: 1
Reputation: 47
i think this would work
handleClick(e) {
const { param } = e.target.dataset;
console.log(param);
}
Upvotes: 0