I'm a beginner in React.js and need some help.
I want to get the value or data from a <li>
-tag when you click on it. How can I do that?
...
clickOnMe : function () {
this.setState({myData : event.target.value});
}
render : function (){
return (
<div>
<ul>
<li value="Point" onClick={this.clickOnMe}>Point</li>
</ul>
</div>
);
}
...
I'm a beginner in React.js and need some help.
I want to get the value or data from a <li>
-tag when you click on it. How can I do that?
...
clickOnMe : function () {
this.setState({myData : event.target.value});
}
render : function (){
return (
<div>
<ul>
<li value="Point" onClick={this.clickOnMe}>Point</li>
</ul>
</div>
);
}
...
Share
Improve this question
edited Sep 13, 2018 at 19:14
divibisan
12.2k11 gold badges43 silver badges62 bronze badges
asked Apr 20, 2016 at 8:13
Earl MeggetEarl Megget
381 gold badge1 silver badge7 bronze badges
1
- 1 Do you want to have access to property that is under your control (so you can put it in props or state, or make const), or it's from DOM? – iofjuupasli Commented Apr 20, 2016 at 8:34
1 Answer
Reset to default 2You're getting undefined
because target.value
is only used for form elements such as input
.
You can pass the function a unique identifier, which you then can use to fetch it's value from this.state
.
Implementations may vary a lot. The biggest question would probably depend on whether or not the value of this element can change in the DOM, or if will remain static at all times.
Here are my proposed solutions for both:
Element can change value in DOM:
If you want to update the value of your li
element, you can do this:
getInitialState: function() {
return {
data: ["point1", "point2", "point3"];
};
}
clickOnMe = (id) => {
console.log(this.state.data[id]);
}
changeData = (id, value) => {
let temp = this.state.data.slice();
temp[id] = value;
this.setState({temp});
}
render = () => {
return (
<div>
<ul>
<li value={this.state.data[0]} onClick={this.clickOnMe.bind(this, 0)}>Point</li>
</ul>
</div>
);
}
this.state.data
is an array that is in the ponents constructor and contains the initial values for each element. When you click on an element, you'd call the clickOnMe
function and pass in a parameter that corresponds to the index in the array in which the data for the current element is.
If you want to change this value later, you can call changeData
with the value and index as parameters. Make a copy of the entire array, change the value in said index, then update the state
.
Element is static in DOM:
If the value of li
is always static, then you can do:
clickOnMe = (val) => {
this.setState({myData : val});
}
render = () => {
return (
<div>
<ul>
<li onClick={this.clickOnMe.bind(this, "Point")}>Point</li>
</ul>
</div>
);
}
If you want things to be static, things are much simpler. Here you can just directly bind which value corresponds to said element, and then in the function do what you want with it.