user3142695
user3142695

Reputation: 17362

How to pass variable in a function call?

In my functional component I'm calling two functions, which are doing nearly the same thing:

const App = () => {
    const handleOnClickFirst = () => {
      setValue('first')
    }
    const handleOnClickSecond = () => {
      setValue('second')
    }

    return (
        <div>
            {anything === true
            ? <Button onClick={handleOnClickFirst} />
            : <Button onClick={handleOnClickSecond} />}
        </div>
    )
}

So there should be simply only

const handleOnClick = (value) => {
    setValue(value)
}

But how do I pass the value in onClick?

Upvotes: 0

Views: 334

Answers (4)

Harmandeep Singh Kalsi
Harmandeep Singh Kalsi

Reputation: 3345

You can do this :

<button onClick={(event)=>handleOnClick(<pass your paramter here>)}></button>

Upvotes: 1

Armen
Armen

Reputation: 89

As we know with JSX you pass a function as the event handler. So we can wrap our handler with another function and call handler with arguments in this wrapper function

onClick={(event) => handleOnClick(value)}

or for old versions we can do

onClick={function(event){ handleOnClick(value) }}

If you don't need events you can just pass it like this

onClick={() => handleOnClick(value)}

Also if it is a Class base component we use bind to pass method context and arguments

class App extends React.Component {
  handleOnClick(val) {
    console.log(`${val}`);
  }
  render() {
    return (
      <button onClick={this.handleOnClick.bind(this, "test")}>
        click me
      </button>
    );
  }
}

Upvotes: 2

Alfonso Piedrasanta
Alfonso Piedrasanta

Reputation: 13

Try this:

const App = () => {
     const handleOnClick = (passedInValue) => {
          setValue(passedInValue)
     }
     return (
          <div>
               {anything === true
               ? <Button onClick={() => handleOnClick("first")} />
               : <Button onClick={() => handleOnClick("second")} />}
          </div>
      )
    }

Upvotes: -1

Arbin Shrestha
Arbin Shrestha

Reputation: 155

You could do

 onClick={() => handleOnClick(value)}

edit:

More information here: https://reactjs.org/docs/faq-functions.html

Upvotes: 1

Related Questions