Skip to content
react

Handling onClick event in React with examples

Oct 9, 2021Abhishek EH4 Min Read
Handling onClick event in React with examples

In this article, we will see how to handle onClick events in React, from calling a function to passing value from a list.

Calling a function when a button is clicked

1import React from "react"
2
3const CallAFunction = () => {
4 const showAlert = () => {
5 alert("Hello")
6 }
7 return (
8 <div>
9 <button onClick={showAlert}>Click Me!</button>
10 </div>
11 )
12}
13
14export default CallAFunction

Consider the above component, in order to call a function in React when a button is clicked, we just need to pass the function to the onClick prop of the button.

Do not call the function while passing it as prop like onClick={showAlert()}. If you pass like this, then the function will be called immediately when the page is loaded.

You can test the code in the below demo:

Calling an inline function

If your function has only one line (or very few) then you can execute it inline rather than defining it separately:

1import React from "react"
2
3const App = () => {
4 return (
5 <div>
6 <button onClick={() => console.log("Hello")}>Click Me!</button>
7 </div>
8 )
9}
10
11export default App

Since the function has only one line, we have used the "concise body" without the brackets. If there are more than one line in the function, then we can write it as follows:

1import React from "react"
2
3const App = () => {
4 return (
5 <div>
6 <button
7 onClick={() => {
8 console.log("Hello")
9 alert("Hello")
10 }}
11 >
12 Click Me!
13 </button>
14 </div>
15 )
16}
17
18export default App

Updating a state on click of a button

In the below code, we have written an arrow function, which will increment the counter by 1 each time the user clicks on the button.

1import React, { useState } from "react"
2
3const UpdateState = () => {
4 const [counter, setCounter] = useState(0)
5 return (
6 <div>
7 <p>Counter: {counter}</p>
8 <button onClick={() => setCounter(counter + 1)}>Increment</button>
9 </div>
10 )
11}
12
13export default UpdateState

You can try out the example below:

Counter: 0

Alternatively, you can define a function and call setCounter inside it:

1import React, { useState } from "react"
2
3const UpdateState = () => {
4 const [counter, setCounter] = useState(0)
5 const incrementCounter = () => {
6 setCounter(counter + 1)
7 }
8 return (
9 <div>
10 <p>Counter: {counter}</p>
11 <button onClick={incrementCounter}>Increment</button>
12 </div>
13 )
14}
15
16export default UpdateState

Pass button value to a function

You can access the value of the button by calling e.target.value inside the event handler as shown below:

1import React from "react"
2
3const PassAValue = () => {
4 const handleClick = e => {
5 alert(e.target.value)
6 }
7 return (
8 <div>
9 <button value="Welcome to CodingDeft!" onClick={handleClick}>
10 Click Me!
11 </button>
12 </div>
13 )
14}
15
16export default PassAValue

Click on the following button to see what is displayed:

Passing a value from the list when clicked

If you would like to pass a value from the list, you can do it as shown in the below code (styles are removed for simplicity):

1import React, { useState } from "react"
2
3const numbers = [29, 75, 36]
4
5const ChooseNumber = () => {
6 const [chosenNumber, setChosenNumber] = useState()
7
8 const handleClick = value => {
9 setChosenNumber(value)
10 }
11
12 return (
13 <div>
14 <p>
15 {chosenNumber ? `Chosen Number: ${chosenNumber}` : "Chosen a Number"}
16 </p>
17 <div>
18 {numbers.map(number => (
19 <div onClick={() => handleClick(number)} key={number}>
20 {number}
21 </div>
22 ))}
23 </div>
24 </div>
25 )
26}
27
28export default ChooseNumber

In the above code, we loop through an array of numbers and display them within boxes. When the user clicks on the box, we pass that number to the handleClick function and update the state chosenNumber.

You can test the example in the below demo:

Chosen a Number

29
75
36

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

Leave a Comment

© 2024 CodingDeft.Com