Skip to content
react

How to pass a parameter through onClick in React

Jul 6, 2022Abhishek EH2 Min Read
How to pass a parameter through onClick in React

In this article, we will see how to pass a value to a function when the user clicks on an HTML element.

In one of my previous articles, I've explained how to handle onClick events in React.

Passing a constant value

If you need to pass a static value when the user clicks on the element, you can do so by using the following code:

App.js
1function App() {
2 const handleClick = value => {
3 console.log(value) //👉️ John
4 }
5 return (
6 <div className="App">
7 <button onClick={() => handleClick("John")}>Click Me</button>
8 </div>
9 )
10}
11
12export default App

Here we are using an arrow function to call the handleClick function. You can pass as many parameters as you want to the handleClick function.

Accessing the value of the element

If you need to access the value of the element you can do so by accessing the e.target.value, where e is the click event reference in this context.

App.js
1function App() {
2 const handleClick = value => {
3 console.log(value) //👉️ John
4 }
5 return (
6 <div className="App">
7 <button value="John" onClick={e => handleClick(e.target.value)}>
8 Click Me
9 </button>
10 </div>
11 )
12}
13
14export default App

Accessing the data-* attributes

If you need to access the data-* attribute, you can do so using the following code:

App.js
1function App() {
2 const handleClick = e => {
3 const dataSet = e.target.dataset
4 const value = e.target.innerHTML
5
6 alert("The " + value + " is a " + dataSet["animalType"]) // Note how Kebab case turned into camel case
7 }
8 return (
9 <div className="App">
10 <ul>
11 <li onClick={handleClick} key="owl" data-animal-type="bird">
12 Owl
13 </li>
14 <li onClick={handleClick} key="salmon" data-animal-type="fish">
15 Salmon
16 </li>
17 <li onClick={handleClick} key="tarantula" data-animal-type="spider">
18 Tarantula
19 </li>
20 </ul>
21 </div>
22 )
23}
24
25export default App

In the above example, we are directly passing the handleClick function to the onClick handler and it will receive the click event as the first parameter. In the handleClick function, we are accessing both the list's content and the animal-type data property.

If you have liked article, do follow me on twitter to get more real time updates!

Leave a Comment

© 2022 CodingDeft.Com