Earl Megget
Earl Megget

Reputation: 38

How to get value from <li> tag

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

Upvotes: 2

Views: 15085

Answers (1)

Chris
Chris

Reputation: 59501

You'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 components 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.

Upvotes: 2

Related Questions