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.
In this solution inside onClick
event handler we call the sayHello
method with a string as an argument.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const sayHello = (name) => {
7
console.log(`hello ${name}!`);
8
console.log(`(Tom - ${typeof name})`);
9
};
10
return <button onClick={() => sayHello('Tom')}>Greet</button>;
11
};
12
13
const root = document.querySelector('#root');
14
ReactDOM.render(<App />, root);
In this solution, we pass button
element's value
to the sayHello
function.
Runnable example:
xxxxxxxxxx
1
// Note: Uncomment import lines while working with JSX Compiler.
2
// import React from 'react';
3
// import ReactDOM from 'react-dom';
4
5
const App = () => {
6
const sayHello = (name) => {
7
console.log(`hello ${name}!`);
8
console.log(`(${name} - ${typeof name})`);
9
};
10
return (
11
<button value="Tom" onClick={e => sayHello(e.target.value)}>Greet</button>
12
);
13
};
14
15
const root = document.querySelector('#root');
16
ReactDOM.render(<App />, root);