Table of Contents
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:
1function App() {2 const handleClick = value => {3 console.log(value) //👉️ John4 }5 return (6 <div className="App">7 <button onClick={() => handleClick("John")}>Click Me</button>8 </div>9 )10}1112export 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.
1function App() {2 const handleClick = value => {3 console.log(value) //👉️ John4 }5 return (6 <div className="App">7 <button value="John" onClick={e => handleClick(e.target.value)}>8 Click Me9 </button>10 </div>11 )12}1314export default App
Accessing the data-* attributes
If you need to access the data-* attribute, you can do so using the following code:
1function App() {2 const handleClick = e => {3 const dataSet = e.target.dataset4 const value = e.target.innerHTML56 alert("The " + value + " is a " + dataSet["animalType"]) // Note how Kebab case turned into camel case7 }8 return (9 <div className="App">10 <ul>11 <li onClick={handleClick} key="owl" data-animal-type="bird">12 Owl13 </li>14 <li onClick={handleClick} key="salmon" data-animal-type="fish">15 Salmon16 </li>17 <li onClick={handleClick} key="tarantula" data-animal-type="spider">18 Tarantula19 </li>20 </ul>21 </div>22 )23}2425export 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, stay in touch with me by following me on twitter.
Leave a Comment