Oscar Arranz
Oscar Arranz

Reputation: 714

How to set onClick event of button to multiple functions (depending on prop) in React?

I have a custom button which renders a button like this:

<button>{this.props.text}</button>

This button is called ButtonCustom, what I want to do in the render method of the main container is this:

function myFunc1{
    doSomething();
}
function myFunc2{
    doSomething();
}

<ButtonCustom text="sometext" onClick={myFunc1}></ButtonCustom>
<ButtonCustom text="sometext" onClick={myFunc2}></ButtonCustom>

This however isn't working as the button doesn't execute the functions, how could I make it work?

Upvotes: 0

Views: 110

Answers (1)

Jose A. Ayll&#243;n
Jose A. Ayll&#243;n

Reputation: 886

You have to also pass as props the onCLick function to your custom button:

export const ButtonCustom = ({ onClick, text }) => (
    <button type="button" onClick={onClick}>
        {text}
    </button>
);

Now you'll be able to fire the onClick event in your button:

<ButtonCustom text="sometext" onClick={myFunc1}></ButtonCustom>

Bear in mind that if you have a custom component in react, nothing will be automatically injected in the render code unless you explicitly pass it as props

Upvotes: 2

Related Questions