Languages
[Edit]
EN

React - how to pass variable to method

0 points
Created by:
May87
427

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 );

ReactJS

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.

â€ïžđŸ’» 🙂

Join