EN
React - how to pass string variable to a function with onClick
3
points
In this article, we would like to show you how to pass a string variable to a function with onClick
in React.
Below we present two solutions for the problem:
- calling the function with a string argument,
- using event target value.
1. Calling the function with a string argument
In this solution inside onClick
event handler we call the sayHello
method with a string as an argument.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const sayHello = (name) => {
console.log(`hello ${name}!`);
console.log(`(Tom - ${typeof name})`);
};
return <button onClick={() => sayHello('Tom')}>Greet</button>;
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);
2. Using event target value
In this solution, we pass button
element's value
to the sayHello
function.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';
const App = () => {
const sayHello = (name) => {
console.log(`hello ${name}!`);
console.log(`(${name} - ${typeof name})`);
};
return (
<button value="Tom" onClick={e => sayHello(e.target.value)}>Greet</button>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);