Calling onClick on the button in render method

I tried to call onClick on the button by doing

<button>Click Me</button>{.onClick(handleClick)}

but it gave an error in the console saying there’s a build error.

I also tried it like this:

const button =
  <button>Click Me</button>;
{button.onClick(handleClick}

but that too had the same result.

So what am I doing wrong?

My code so far


class MyComponent extends React.Component {
constructor(props) {
  super(props);
  this.state = {
    text: "Hello"
  };
  // change code below this line
  this.handleClick = this.handleClick.bind(this);
  // change code above this line
}
handleClick() {
  this.setState({
    text: "You clicked!"
  });
}
render() {
  return (
    <div>
      { /* change code below this line */ }
      <button>Click Me</button>
      
      { /* change code above this line */ }
      <h1>{this.state.text}</h1>
    </div>
  );
}
};

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36 Edg/84.0.522.59.

Challenge: Bind ‘this’ to a Class Method

Link to the challenge:

Okay, never mind. I had forgotten that onClick was a property on the button element. I got it.

2 Likes

Okay so 1st u created a button in HTML
and then added JS
So JS belong in the script tag not the HTML one
I would recomend you to read about the DOM and how to use it correctly
Basicly it goes a bit like this

HTML
create button with ID

JS
use DOM to call upon the ID/class
add ure event lisener in this case u wait until the button is clicked
ON CLICKED
then tell JS to excecute the function

function myFunction() {
  document.getElementById("buttonID").innerHTML
alert = "I am clicked";
}

as for the onClick event:
https://www.w3schools.com/jsref/event_onclick.asp

I already got it. Like I said before, I just forgot that you have to add it as a property on the element. Thanks, anyway, though.