Styled Components & React: Click event

Viewed 13377

I am trying to create an onClick for a Styled Components Component, but it is not working. It is not logging hello in the console.

<Component onClick={this.handleClick} />

The handleClick:

handleClick(e) {
    console.log("hello");
}

This is also in the constructor:

this.handleClick = this.handleClick.bind(this);

The component:

const Component = styled.span`
    /* Regular CSS */
    ${css};
`;

Thanks in advance!

EDIT:

The component is nested in a Button component. When I add the onClick to the Button Component hello is shown in the console. However I want the child to have this function not the parent.

EDIT 2:

Ok so when I change the CSS it works. I have no idea why. This is my css:

        top: 0;
        left: 0;
        width: 10px;
        height: 10px;
        display: block;
        z-index: 0;
        position: absolute;
        overflow: hidden;
        border-radius: inherit;
3 Answers

We probably need more code. Anyway the cleanest way to bind is by arrow functions:

handleClick = () => console.log('click')

If your Button is INSIDE you have to use another props as onClick is binded to onClick event. Try

// In Parent
<Parent action={this.handleClick} />

// In Child
<Child onClick={this.props.action} />

Your span is rendered with a css value of display: inline. If there is no actual content in it to expand, it will be 0 pixels in width, and therefore you are not actually clicking on it.

I ran into the same issues and in Styled Components I couldn't make it work with a forced display: block. You should use a clickable item, like styled.button...

You might want to try this:

handleClick = e => {
  console.log('hello');
}

...

<Component onClick={(e) => this.handleClick(e)} />

or

<Component onClick={this.handleClick.bind(e)}/>
Related