0

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?

1
  • I think you are missing binding this, <ButtonCustom text="sometext" onClick={this.myFunc1.bind(this)}></ButtonCustom>, do the same for other button. Commented May 2, 2019 at 11:44

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

How will myFunc1 will get execute without binding this?
If you use an arrow function, you don't need to bind it. Just do const myFunc1 = _ => { doSomething(); }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.