Home > Net >  Pass the element itself as an onClick parameter instead of an instance of a class
Pass the element itself as an onClick parameter instead of an instance of a class

Time:12-10

I need to change the inner text of a button that is rendered by a class. Because of that, when I use the this keyword, React imagine that I want to pass the object of that class instead of the element itself.

Here I have my sample React code that doesn't work:

class Component extends React.Component {
    
    helloWorld(element) {
        element.innerText = 'Hello Wolrd!';
    }
    render() {
        return (
            <button onClick={this.helloWorld(this)}>Change it!</button> 
        )
    }
}

And here I have a vanila JavaScript code that gets the expected result

<button onclick=helloWorld(this)>Change it!</button> 
<script>
  function helloWorld(element) {
    element.innerText='Hello World!';
  }
</script>

CodePudding user response:

The keyword this in a React component refers to the component itself as you guessed. You need to add a parameter event to the onClick method :

<button onClick={(e) => this.helloWorld(e.target)}>Change it!</button>
  • Related