PrettyBiased
PrettyBiased

Reputation: 137

How can I pass multiple props in a single event handler in ReactJS?

I'm trying to add a onClick listener to a li and the props will be passed to another component that will eventually call a function. My first thought was simply put 2 onClick, but I got a warning for duplicate props.

<li onClick={props.headlinesClicked} onClick={props.getData}>Top Headlines</li>

Then I tried the vahnilla JS way but I assume it's not working because these are expressions rather than actual functions.

 <li onClick={() => {{props.headlinesClicked}; {props.getData}}}>Top Headlines</li>

How can I pass these multiple props in a single onClick?

Upvotes: 5

Views: 6895

Answers (4)

Asomba Chinoso
Asomba Chinoso

Reputation: 51

Say you want to do this via a button onClick event,

On the btn, I want to pass 3 different kinds of props.

 <Button variant="contained" color="primary" onClick={() => handleClick(`${row.id}`, row.original, myData)}>EDIT</Button>

On the function, retrieve them like this

    function handleClick(idProps, origProps, myDataProps) {
        console.info(`here are the values`, idProps, origProps, myDataProps)
    }

Upvotes: 0

Manos Vajasan
Manos Vajasan

Reputation: 1

I have recommended below way it will work 100%

const handleListItemClick = () => {

if(props.headlinesClicked){

props.headlinesClicked()

}else{ props.getData() }

return <li onClick={handleListItemClick}>Top Headlines</li>

Note:react have confuse two props we mentioned same onClick .

Upvotes: 0

Dom
Dom

Reputation: 1816

Your first snippet won't work as you can't bind to a prop multiple times. The second is incorrect firstly because anything inside the brackets is JS, so the additional brackets inside are unnecessary and you're also not invoking any of the functions.

Think of it this way, onClick={props.headlinesClicked} is kind of like a shorthand for onClick={() => props.headlinesClicked()} (not exactly as onClick also passes an event as the first parameter, but hopefully you get the gist of it). So, when you do onClick={() => props.headlinesClicked} you're not actually calling the function, just returning a reference to it which then doesn't actually do anything.

You could either do onClick={() => props.headlinesClicked(); props.getData()}, or extract it to a new function/method that does both calls, then invoke it with onClick={myNewMethod} or onClick={() => myNewMethod()}.

Upvotes: 2

kingdaro
kingdaro

Reputation: 11998

Have the passed function call the other two functions normally:

<li onClick={() => { props.headlinesClicked(); props.getData() }}>Top Headlines</li>

Alternatively (recommended for readability), make a new function which calls those two functions. Consider making the function a class method if it's a class component.

const handleListItemClick = () => {
  props.headlinesClicked()
  props.getData()
}

return <li onClick={handleListItemClick}>Top Headlines</li>

Upvotes: 2

Related Questions