Merlin -they-them-
Merlin -they-them-

Reputation: 2960

Dynamic Component onClick not working

I have a JS Fiddle with the below code.

I have a dynamic component setup, which does work. If I do var Component = Switch or set Component to some other React component, it works. But I want to be able to have it switch when I click on it.

So I set up an onClick event. Yet its not firing. I get no log statements or any change. Any ideas why?

var Other = React.createClass({
  render: function () {
    return <h2>Test this craziness</h2>;
  }
});

var Switch = React.createClass({
  render: function () {
    return <h2>A different one to switch with</h2>;
  }
});

var Hello = React.createClass({
  getInitialState: function() {
    return {on: true};
  },
  handleClick: function() {
    console.log('handleclick');
    this.setState({on: ! this.state.on});
  },
  render: function() {
    console.log(this.state);
    var Component = this.state.on ? this.props.component.name : Switch;
    return <Component onClick={this.handleClick} />;
  }
});

ReactDOM.render(
  <Hello component={{name: Other}} />,
  document.getElementById('container')
);

Upvotes: 1

Views: 702

Answers (2)

danmakenoise
danmakenoise

Reputation: 294

Easy! When onClick is put directly on a Component, like you have done, it is NOT set as the onClick function. It is instead placed in this.props.onClick. You still need to add the onClick to your actual DOM Elements. See the attached JSFiddle!

Upvotes: 1

FuriousD
FuriousD

Reputation: 854

You need to add the onClick attribute to an actual HTML element, i.e.

var Other = React.createClass({
  render: function () {
    return <h2 onClick={this.props.onClick}>Test this craziness</h2>;
  }
});

Upvotes: 1

Related Questions