React - how to pass variable to method

0 points
Created by:

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 );
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.


React - pass variable to method
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂