How To Pass Event And Parameter OnClick In React

Pass event and parameter onClick in React

Passing event and parameter onClick in React will help you to manipulate and work with DOM elements. To do that you need to know about onClick attribute or some other function. So how to do it? Let’s go into detail.

Pass event and parameter onClick in React

Understanding onClick

React provided the onClick attribute that can help you catch if the user clicks on your elements. Then you can execute your logic code if the onClick is triggered.

Syntax:

onClick={{callback(e)}}

Parameters:

  • callback: The callback would be triggered when an element is clicked.
  • e: Stands for ‘event’ containing all properties related to an event that happens to an element.

The ‘event’ parameter in onClick has all properties that look like this:

Example:

import './App.css';

function App() {
    return (
        <div className="App">
            <h1 >Hello From Learn Share IT</h1>
            <button onClick={(e) => { console.log(e); }}>Click Me</button>
        </div>
    );
}

export default App;

Output:

With this example, we can access our element through the target property, which is the button element.

Example for onClick

Example:

import { useState } from 'react';

function App() {
    const [count, setCount] = useState(0);
  
    return (
        <div className="App">
            <h1>Hello From Learn Share IT</h1>
            <button 
                onClick={(e) => {
                    setCount(count + 1);
                    console.log(count);
            	}}
            >Click Me</button>
        </div>
    );
}

export default App;

Output:

Before click:

After click:

Or you can also pass in an already function.

Example:

import { useState } from 'react';

function App() {
    const [count, setCount] = useState(0);
    const handleClick = (e) => {
        (e) => {
            setCount(count + 1);
            console.log(count);
        };
    };
    
    return (
        <div className="App">
            <h1>Hello From Learn Share IT</h1>
            <button onClick={handleClick}>Click Me</button>
            <h1>{count}</h1>
        </div>
    );
}

export default App;

Here I make a logic that every time I click a button, the count state value will be plus with 1.

Summary

In this article, I’ve shown you how to pass event and parameter onClick in React. You can pass in an arrow function without a name into onClick directly or can create a function outside and then pass it in. Thanks for reading!

Maybe you are interested:

Leave a Reply

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