1

I'm migrating a react app to ES6 and moving events so they're bound in the constructor, here's a very basic example:

import React from 'react';
import ReactDom from 'react-dom';

export default class Button extends React.Component {
    constructor() {
        super();
        this.click = this.click.bind(this);
    }
    click() {
        alert('hi');
    }
    render() {
        return (
            <button onClick={this.click}>click</button>
        );
    }
}

if(typeof window !== 'undefined') {
    ReactDom.render(<Button/>, document.getElementById('button-spot'));
}

The button renders correctly, and there aren't any server/client errors, but when I click this button, nothing happens. I also tried console.log() and its not logging. Am I doing the event.bind(this) binding wrong?

more context:

my index.js router:

router.get('/', function(req, res, next) {
    res.render('index', { 
        button: ReactDom.renderToString(<Button/>)
    });
});

html page:

<div id='button-spot'><%-button%></div>

EDIT


I tried Andre's suggestion below

onClick={x => alert(1)}

and the event isn't firing, what could the issue be?

Abdul Ahmad
  • 9,673
  • 16
  • 64
  • 127
  • 1
    have u tried place the function inline there to check if the event is being triggered? like: `onClick={x => alert(1)}` – André Junges May 05 '16 at 17:53
  • @AndréJunges no but I can try! – Abdul Ahmad May 05 '16 at 17:54
  • @AndréJunges its not being triggered – Abdul Ahmad May 05 '16 at 17:57
  • with an ES2015 class your methods are already bound to `this`, so that line shouldn't be required at all. – Nathan Cox May 05 '16 at 17:57
  • @NathanCox the click event is being bound, not the method – Abdul Ahmad May 05 '16 at 17:59
  • It still shouldn't be required. React has already handled event binding for you via the `onClick` attribute. The only thing you should need to pass to it is the method itself, which you've already done via `onClick={this.click}`. I've never had React require me to manually bind events for any component. – Nathan Cox May 05 '16 at 18:07
  • @NathanCox so why does every tutorial say to do it? – Abdul Ahmad May 05 '16 at 18:09
  • As far as I know, binding is only required if you're actually using `this` inside of the method itself to reference the component class (which would be normally), but in this example you aren't. The point I'm trying to make is that binding `this` to it doesn't seem to be your problem, the actual event propagation would be. Especially if `onClick={() => alert('hi')}` isn't working for you (which would also bind the component scope to the method). – Nathan Cox May 05 '16 at 18:19

1 Answers1

0

Unfortunately, when using DOM event handlers, you can't render React only from the server. You either need to render both client/server React code or use a server-side rendering solution that addresses that problem directly.

Here are a few good starting points:

Community
  • 1
  • 1
lovelikelando
  • 7,593
  • 6
  • 32
  • 50