SuperCoolDude1337 SuperCoolDude1337 - 4 years ago 197
React JSX Question

onClick not being called ReactJS

Before downvoting, I've been through plenty of other solutions on SO around this same issue and can't find an answer that resolves this issue.

I'm having trouble trying to get the onClick attribute to fire off my function, here's a piece from the problematic component:

Constructor:

constructor() {
super();
this.state = {
submissionFormCount: 0
}
this.addToSubmissionFormCount = this.addToSubmissionFormCount.bind(this);
}


render:

<div className="row">
<div className="col s12 m12 l12">
<h5 onClick={this.addToSubmissionFormCount} style={beatSubmissionStyles.colorize}><span>(Plus) </span>add another beat</h5>
</div>
</div>


clickHandler:

addToSubmissionFormCount() {
alert('Here');
this.setState({
submissionFormCount: this.state.submissionFormCount++
});
}


I'm rendering the app from an Express server using 'react-dom/server'

Here's how I am rendering the component:

exports.beatSubmission = (req, res) => {
const appString = renderToString(<App type="beatSubmission"/>);
res.send(beatSubmissionTemplate({
body: appString
}))
}

Answer Source

I think you're only rendering your react components on the server side. The reason I think this is because of the following code you've copied:

exports.beatSubmission = (req, res) => {
    const appString = renderToString(<App type="beatSubmission"/>);
    res.send(beatSubmissionTemplate({
        body: appString
    }))
}

You're rendering the component to a string and shipping the string to the frontend as static HTML. While this will indeed give you properly rendered markup, it will result in a non-interactive app.

To have click handlers work, you also need to compile your JS, and include it for use on the frontend like this:

https://github.com/erikras/react-redux-universal-hot-example/blob/master/src/server.js#L76 renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>));

There are a few ways to do this. You can manually add a script file with your JS pre-packaged for the frontend in your template or you can use Webpack Isomorphic Tools.

I suspect you read a react tutorial that lead you down the isomorphic (server/client side rendered) path. You can run react on the server, the client side or both. Running it on both takes some work, but results in an app that "feels" faster.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download