Categories
React Answers

How to fix onClick being called on render with React?

Spread the love

Sometimes, we want to fix onClick being called on render with React.

In this article, we’ll look at how to fix onClick being called on render with React.

How to fix onClick being called on render with React?

To fix onClick being called on render with React, we can set the onClick prop to a function reference.

For instance, we write

const Square = ({ value }) => {
  return (
    <button className="square" onClick={() => alert("click")}>
      {value}
    </button>
  );
};

to set the onClick prop to a function that shows an alert box.

The function is called only when we click the button since we pass in the function’s reference rather than its returned value.

Conclusion

To fix onClick being called on render with React, we can set the onClick prop to a function reference.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *