2

I wonder if there is a way to pass values to a function such as "onClick". The following code is not to be considered due to performance considerations:

<div onClick={() => handleClick(value)}/>

I'd like to write:

<div onClick={handleClick(value)}/>

But this ain't possible in React. Any solutions?

1
  • The first is a function definition, passing as a callback. The second will be executed and its result, return value will be assigned to onClick event. Commented Sep 18, 2020 at 17:47

2 Answers 2

4

actually it is possible: you need to return a function that do your work. something like this:

const handleClick = value => () => {
// your logic
}

then use it like this:

<div onClick={handleClick(value)}/>
Sign up to request clarification or add additional context in comments.

4 Comments

It's great!. But, it works around and it's not same with: <div onClick={() => handleClick(value)}/>.
it is actually the same, you are returning a function after all.
Yes, absolutely same!
do a console log to be sure if you want
0

Yes, if your callback of a prop such as: onClick will pass a param event when it call. In this case, just pass a function name. Example:

const Comp = (props) => {
    const [value, setValue] = useState(0);
    const handleClick = (event) => {
        setValue(value + 1);
    }

    return <div>
        <div> {value} </div>
        {/*pass function name that declare of function have one param or don't have any pram*/}
        <button onClick={handleClick} > Click me</button>
    </div>
} 

4 Comments

But what do you solve here? You don't pass arguments to handleClick
It will pass a function name. That function is used to call back when click.You can imagine, when you click button, somewhere in button controller will use the function name you passed. And then, it pass an event to function and call handleClick(event).
Yeah ok. But where is the part that you pass an argument additionally to the event? Let's say you'd like: const handleClick = (x, y, z) => { // some code }
Because x,y,z may outer scope like what you have used in above. You can use it in function handleClick instead of pass it in function. What you need to pass in function is variable to pass after click like event. Same as with onClick={(event) => handleClick(value)}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.