5

I have difficulties to attach dynamic events to my react components. I have the following components:

var ListItem = React.createClass({
    render: function() {
        return (
            <li className="selector" >
                <div className="column">
                    <h2 className="commentAuthor">
                        {this.props.author}
                    </h2>
                    <div>{this.props.children}</div>
                </div>
            </li>
        );
    }
});

var ListBox = React.createClass({
    mixins : [MyMixin],

    render : function() {
        this.nodes = this.props.data.map(function(item) {
            return <ListItem author={item.author}>{item.text}</ListItem>;
        });
        return (
            <ul id="columns">
                {this.nodes}
            </ul>
        );
    }
});

As you see the ListItem has className set to "selector". Base on this "selector" I want to query nodes and attach dynamically events in the MyMixin.

React.renderComponent(
    <ListBox data={data} selector="li.selector" />,
    document.getElementById('example')
);

Maybe my idea is all wrong as I'm fairy new to React.

Regards

Dmitry Shvedov
  • 3,169
  • 4
  • 39
  • 51
user732456
  • 2,638
  • 2
  • 35
  • 49

1 Answers1

6

You should listen to events directly on the ListItem component. React doesn't want you to think about attaching listeners later.

var ListItem = React.createClass({
    handleClick: function(event) {
      // Handle ListItem click
    },
    handleDoubleClick: function(event) {
      // Handle ListItem double click
    },
    render: function() {
        return (
            <li className="selector"
                    onClick={this.handleClick}
                    onDoubleClick={this.handleDoubleClick}>
                <div className="column">
                    <h2 className="commentAuthor">
                        {this.props.author}
                    </h2>
                    <div>{this.props.children}</div>
                </div>
            </li>
        );
    }
});

React expects the attributes to exactly match the event name. You can check out the full list of supported events to make sure you use the right names.

Ross Allen
  • 43,772
  • 14
  • 97
  • 95
  • 1
    yup, if you find yourself wanting to "query", it's likely not the react way – Jared Forsyth Dec 20 '13 at 20:54
  • I came up to this solution also. The only difference is that I moved all event handlers to mixin as I want to share the implementation across different components. – user732456 Dec 21 '13 at 08:41
  • 1
    Be careful of modifying Components' APIs with Mixins. If the Mixin adds new methods to the Component, it can be difficult to reason where functionality lives. I suggest implementing only lifecycle methods, like `componentWillMount`, in Mixins. – Ross Allen Dec 21 '13 at 20:47