Search code examples
reactjsevent-handlingreact-props

Pass multiple onclick handler functions to child component


I have some code below to show the issue. There are two handleClick functions that I want to pass to a child component.

The issue is that each handler will trigger from a separate button element. I don't need both functions to trigger at the same time.

I've tried putting both functions in a single handlerClickOneAndTwo function but that is not correct since I don't want that single function to trigger both handlers.

How can I send both of these handler functions down to the child component?

    const handleClickOne = (e) => {
        //some handler logic
        }));
    };

    const handleClickTwo = (e) => {
        //some handler logic
    };

    return (
        <ChildComponent
            onClick={handleClickOne}
    //I also want to handleClickTwo here but it will trigger from a different button
        />
    );
}

Solution

  • Pass different props for diffrent onClick. Like this:

    const handleClickOne = (e) => {
            //some handler logic
            }));
        };
    
        const handleClickTwo = (e) => {
            //some handler logic
        };
    
        return (
            <ChildComponent
                onClick1={handleClickOne}
                onClick2={handleClickTwo}
            />
        );
    
    

    and in your child component assign these according to you requirement