Search code examples
javascriptreactjsreact-starter-kit

#react-starter-kit React onClick not firing on page


I'm using the React-Starter-Kit and am having an issue with an onClick={this.handleClick} not firing in the browser.

What is happening: The Colorswatches.js component is loading and showing up in the browser but the onClick isn't working. No console logs are showing up.

What I think is the problem: Rendering everything server side and passing to client, client gets static react html with no event bindings.

How do I get the click event to work client side after server side rendering?

EDIT: Updating code with provided example from jgldev

EDIT 2: Added componentDidMount() function. With a console log, still not seeing the log on page load

EDIT 3: My issued was with another part of the React-starter-kit that was bombing out the client side re-render. I marked the first answer as correct.

src/component/ColorSwatches/ColorSwatches.js:

import React, { Component, PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ColorSwatches.scss';

class ColorSwatches extends Component {
    constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
    }
    componentDidMount() {
        console.log('I was mounted');
    }
    handleClick(){
        console.log('I was clicked');
    }
    render(){
        let colorSlices = this.props.colorSlices;
        let sku = this.props.sku;
        let currentSkuIndex = 0

        return (
            <div className='pdpColors'>
                <div className='colorSwatches' >
                    { colorSlices.map((colorSlice, index) => {
                        return (
                            <div title={colorSlice.color} onClick={()=>this.handleClick()}  key={index}>
                                <img src={colorSlice.swatchURL}/>
                            </div>
                        )
                    })}
                </div>
            </div>
        )
    }
}

export default withStyles(ColorSwatches,s);

Solution

  • on the constructor: this.handleClick = this.handleClick.bind(this)

    Then, in the render function:

    onClick={()=>this.handleClick()}