EN
React - how to pass variable to method
0
points
In this article, we would like to show you how to pass a variable into method trigged with event in React.
Below example presents simple sayHello
method which receives only one argument (it is name
argument). Button's onClick
property uses arrow function that wraps sayHello
to make possible to pass 'Alex'
text as an argument.
Runnable example:
// ONLINE-RUNNER:browser;
//Note: Uncomment import lines during working with JSX Compiler.
// import React from "react";
// import ReactDOM from "react-dom";
const App = () => {
const sayHello = (name) => {
console.log(`Hello ${name}!`);
}
return (
<button onClick={() => sayHello('Alex')}>Say Hello!</button>
);
}
const root = document.querySelector('#root');
ReactDOM.render(<App/>, root );