How to pass event and parameter onClick in React

To pass event and parameter onClick in React, declare an event handler function and then pass it to the onClick prop of the element inside an inline arrow function.

Using React onClick event handler you can call a function and trigger an action when a user clicks an element(eg button). 

The event names should be written in camelCase, so the onclick event should be written as onClick in a React app, and, React event handlers should be inside curly braces like onClick={clickHandler}.

Pass the event and parameters

You can pass the event and parameters onClick in React as given below example.

function App() {
	const clickHandler = (event, message) => {
		alert(message);
	}
  	return (
  		<div>
    		<button onClick={(event) => clickHandler(event, "Hello World!")}>Say Hello</button>    	
    	</div>
  	);
}

export default App;

Here we set the inline arrow function (event) => clickHandler(event, "Hello World!") as props to the onClick event handler in the button.

The arrow function takes the event as an argument and calls clickHandler function. You can pass many parameters to the clickHandler function as per our needs.

Pass parameters without event object

You can pass parameters without an event object as given below.

function App() {
	const clickHandler = (message) => {
		alert(message);
	}
  	return (
  		<div>
    		<button onClick={() => clickHandler("Hello World!")}>Say Hello</button>    	
    	</div>
  	);
}

export default App;

Why the warning: Invalid event handler property `onclick`. Did you mean `onClick`

The warning: “Invalid event handler property `onclick`. Did you mean `onClick`” occurs when you give event handler property in lowercase letters. To solve the issue give the event handler property onClick in camelCase letters.

 For example, onclick={clickHandler} will cause an error. It should be in camelCase letters like onClick={clickHandler}.