0

So here is my functional Button component

export const MyButton = (props) => {
    return (
        <button className="myButton">{props.text}</button>
    )
}

And I used it in another page like

<MyButton text="Update" onClick={this.checkIt} />

Where that checkIt function is just console logging the state of the class I used it in. But for some reason, it isn't registering the click at all. How can I go about solving it? I implemented in a similar way for input field where I used the props.onChange(event.target.value) and that is working properly.

1
  • Finally, your dom element should receive a handle. In your case, you should assign a handle to <button /> Commented Aug 24, 2020 at 9:41

2 Answers 2

4

You should attach events in child components, otherwise it's not bind to actual UI at all!

Solution 1:

export const MyButton = ({text, ...others}) => {
    return (
        <button className="myButton" {...others}>{text}</button>
    )
}

Solution 2:

export const MyButton = ({text, onClick}) => {
    return (
        <button className="myButton" onClick={onClick}>{text}</button>
    )
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can't use onClick on MyButton component directly because MyButton component isn't a Native DOM element it is just another REACT component and onClick is treated as another property MyButton Component. What you need to do is, inside of MyButton component pass the onClick component to DOM element Button

export const MyButton = (props) => {
  return (
    <button className="myButton" onClick={props.onClick}>{props.text}</button>
   )
}

Comments

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.