2

How to get value of element that was clicked? event.target.value shows undefined.

import React from "react";

class Home extends React.Component{
    constructor(){
        super()
        this.state = {
            products: [],
            isLoaded: false,
            value: ""
        }
        this.handleClick = this.handleClick.bind(this);
    }

   componentDidMount(){
       fetch("/home")
       .then(res => res.json())
       .then(result =>{
           return(
               this.setState({
                   products: result,
                   isLoaded: true
               })
           )                                            
       })
   }

   handleClick(event){
       console.log(event.target) //shows full element
       console.log(event.target.value) //shows undefined    
   }
   
   render(){
      if(!this.state.isLoaded){
          return(
              <h1>Loading...</h1>
          )
      }
      return <div>{this.state.products.map(elements => 
                <div 
                        key={elements.id} 
                        onClick={this.handleClick}
                        value={elements.name}    
                        >
                        {elements.name}
                </div>
                )}
                <h1>Name: {this.state.value}</h1>
            </div>;
    }
}
export default Home;
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
Mirzad
  • 25
  • 2
  • 6
  • Hey, @mirzad, as `event.target` is the clicked `
    ` there is no value in `
    `
    – greenlikeorange Apr 15 '20 at 14:54
  • 1
    An alternative to all the answers is using a `data-value` attribute in the element. Then in the event handler use `event.target.getAtttribute("data-value")`. Yet another alternative is to bind the value as a parameter to the event handler: `onClick={handleClick.bind(this, elements.name)}`. As you can see a lot of possibilities. – Rodrigo Apr 15 '20 at 14:57

2 Answers2

2

<div> tag doesn't have a value, you need to pass the value prop yourself:

<div 
  key={elements.id} 
  onClick={() => this.handleClick(elements.name)} // Pass as parameter
  value={elements.name} // Can be removed if there's no other purpose
  >
  {elements.name}
</div>

And in the function:

handleClick(value){
   console.log(value) // this is the value
}
Anurag Srivastava
  • 14,077
  • 4
  • 33
  • 43
1

A divcomponent does not any value property, you should do something like this to achieve what you need:

<div
  key={elements.id}
  onClick={() => this.handleClick(element.name)}
>
  {elements.name}
</div>
Emanuele Scarabattoli
  • 4,103
  • 1
  • 12
  • 21