jedireza / hapi-react-views

:package: A hapi view engine for React components
MIT License
231 stars 33 forks source link

React: onClick does not work #52

Closed sebbel closed 8 years ago

sebbel commented 8 years ago

I cannot use onClick within a view. Maybe I am doing it wrong.

Code to reproduce

var React = require('react')

class Hello extends React.Component {

  handleClick() {
    console.log("click")
  }
  render() {
    return (
      <button onClick={this.handleClick}>Hello</button>
    )
  }
}

module.exports = Hello

hapi: 13.3 hapi-react-views: 7.0 react: 15.0.2

jedireza commented 8 years ago

Thanks for opening an issue. I started by testing the remount example and added an onClick to the app.jsx component:

var React = require('react');

var Component = React.createClass({
    onClick: function () {
        alert('hi there');
    },
    render: function () {
        return (
            <div onClick={this.onClick}>Foo: ({this.props.foo})</div>
        );
    }
});

module.exports = Component;

And this worked as I expected. I noticed that you're using class syntax and IIRC you may need to bind to this when attaching the handler, like:

var React = require('react')

class Hello extends React.Component {

  handleClick() {
    console.log("click")
  }
  render() {
    return (
      <button onClick={this.handleClick.bind(this)}>Hello</button>
    )
  }
}

module.exports = Hello

Let me know if that works/helps.

sebbel commented 8 years ago

Thanks for your example :) I was trying it on the simple layout to no avail. I will remodel my application to follow the remount-example and take it from there.

jedireza commented 8 years ago

Ok great. I'll close this for now. Open n issue anytime.