Languages
[Edit]
EN

React - how to pass string variable to a function with onClick

3 points
Created by:
Dexter
660

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

Alternative titles

  1. React - pass parameter through onClick
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.

ReactJS

React - pass string variable to a function with onClick
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