Reputation: 157
I'd like to add onClick event only on an element of the list(array)
class App extends React.Component {
constructor(){
super();
this.state = {
list: ['Value1','Value2']
}
}
render(){
return (
<div className="App">
{this.state.list.map(data => {
return data
})} // How can I add onClick event only on 'Value1' after it rendered?
</div>
);
}
}
My solution is:
const [Value1,Value2] = this.state.list
value1.addEventListener('click',function(){})
but it seems like doesn't work.
Upvotes: 0
Views: 862
Reputation: 114
In React
, you can bind onClick
in the component. You can read more about event handling in here: https://reactjs.org/docs/handling-events.html
Your code can be changed into this:
class App extends React.Component {
constructor() {
super()
this.state = {
list: ['Value1', 'Value2']
}
}
handleClick = e => {
console.log('You clicked the item!!')
}
render() {
return (
<div className="App">
{this.state.list.map(data => {
return (
<span onClick={data === 'Value1' ? this.handleClick : undefined}>
{data}
</span>
)
})}
</div>
)
}
}
Upvotes: 1