Tamn
Tamn

Reputation: 157

What is the right way to add onClick event on element after render?

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

Answers (1)

Mir
Mir

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

Related Questions