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;