0

I am experimenting with styled-components and have seen that we can define a custom component easily such as:

const myButton = ({className, children}) => {
    <button className={className}>{children}</button>
}

However when I am using it in the rendered HTML, I cannot seem to get an event to trigger from the onClick handler attached...

<MyButton onClick={doSomething}>My custom button element</MyButton>

I have also tried attaching onClick to the defined const, including the function in that file:

const myButton = ({className, children}) => {
    <button className={className} onClick="{doSomething}">{children}</button>
}

But neither seem to work...

2 Answers 2

2

You are not passing any reference to onClick function in your component. You should have something like this:

const myButton = ({className, children, onClick}) => {
    <button className={className} onClick={onClick}>{children}</button>
}

In your example of attached onClick method, you attached the string instead of the function. Try something like this if above won't work:

const myButton = ({className, children}) => {
    <button className={className} onClick={() => alert("click!")}>{children}</button>
}
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome, thanks! The basic page didn't spell this out very clearly. My bad.
I also just realised that I have to do this if I wish to add an ID to the tag!
0

Not sure if this right but I think you are trying to call doSomething function right ?

If so try this

<MyButton onClick={this.doSomething}>My custom button element</MyButton>

Or using arrow function

<MyButton onClick={() => this.doSomething}>My custom button element</MyButton>

Or if you are passing as a prop use

<MyButton onClick={props.doSomething}>My custom button element</MyButton>

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.