Ad

Should React Component Delegate OnChange Events To Parent?

- 1 answer

I'am using react with Flux architecture. And I have a question about best practices. We have two component: container and item:

var Contaner = React.createClass({
    getInitialState: function () {
        return {
            items: [ 'hello', 'world' ]
        }
    },
    onClick: function () {
        console.log('clicked!');
    },
    render: function () {
        return 
            <div>
                {this.state.items.map(function (item) {
                    return <Item data={item} onClick={this.onClick} />
                })}
            </div>;
    }
});

var Item = React.createClass({
    getInitialState: function () {
    render: function () {
        return 
            <div>
                <button onClick={this.props.onClick}>{this.props.data}</button>
            </div>
    }
});

So, the question is: should I delegate onClick to parent component (container) or implement it in item component and why?

Ad

Answer

Depends on what you need as this in the click handler. Do you need to access container state or member variables or methods in the click handler? If yes, then by all means define the handler as method of container and pass it to the item as a property. If not, then the logical place for the handler is the item itself.

If you need to access both, for example to alter states of both components, then use both: implement two handlers and have the item onClick handler call the one passed from the parent as a property.

Ad
source: stackoverflow.com
Ad