Home >Web Front-end >JS Tutorial >Why Does an onClick Function Trigger on Render in React and How to Prevent It?
Why Does an onClick Function Fire on Render in React and How to Prevent It?
When passing a list of objects and a delete function to a child component and using a .map() function to display the objects, it's noticed that the button's onClick function triggers during rendering, which should not occur.
To resolve this issue and prevent the onClick function from firing on render:
Explanation:
In the original code, the onClick event handler is called directly instead of being passed as a reference to the function. This means that the function is executed when the component is rendered, rather than when the button is clicked.
Solution:
To fix this, use an arrow function like so:
<button type="submit" onClick={() => { this.props.removeTaskFunction(todo) }}>Submit</button>
Arrow functions, introduced in ES6, allow you to define anonymous functions without having to declare the function keyword explicitly. In this case, the arrow function is not called until the button is clicked, preventing the onClick function from firing on render.
The above is the detailed content of Why Does an onClick Function Trigger on Render in React and How to Prevent It?. For more information, please follow other related articles on the PHP Chinese website!