Reactjs: how to modify dynamic child component state or props from parent?

I'm essentially trying to make tabs in react, but with some issues.

Here's file page.jsx

<RadioGroup>
    <Button title="A" />
    <Button title="B" />
</RadioGroup>

When you click on button A, the RadioGroup component needs to de-select button B.

"Selected" just means a className from a state or property

Here's RadioGroup.jsx:

module.exports = React.createClass({

    onChange: function( e ) {
        // How to modify children properties here???
    },

    render: function() {
        return (<div onChange={this.onChange}>
            {this.props.children}
        </div>);
    }

});

The source of Button.jsx doesn't really matter, it has a regular HTML radio button that triggers the native DOM onChange event

The expected flow is:

  • Click on Button "A"
  • Button "A" triggers onChange, native DOM event, which bubbles up to RadioGroup
  • RadioGroup onChange listener is called
  • RadioGroup needs to de-select button B. This is my question.

Here's the main problem I'm encountering: I cannot move <Button>s into RadioGroup, because the structure of this is such that the children are arbitrary. That is, the markup could be

<RadioGroup>
    <Button title="A" />
    <Button title="B" />
</RadioGroup>

or

<RadioGroup>
    <OtherThing title="A" />
    <OtherThing title="B" />
</RadioGroup>

I've tried a few things.

Attempt: In RadioGroup's onChange handler:

React.Children.forEach( this.props.children, function( child ) {

    // Set the selected state of each child to be if the underlying <input>
    // value matches the child's value

    child.setState({ selected: child.props.value === e.target.value });

});

Problem:

Invalid access to component property "setState" on exports at the top
level. See react-warning-descriptors . Use a static method
instead: <exports />.type.setState(...)

Attempt: In RadioGroup's onChange handler:

React.Children.forEach( this.props.children, function( child ) {

    child.props.selected = child.props.value === e.target.value;

});

Problem: Nothing happens, even I give the Button class a componentWillReceiveProps method


Attempt: I attempted to pass some specific state of the parent to the children, so I can just update the parent state and have the children respond automatically. In the render function of RadioGroup:

React.Children.forEach( this.props.children, function( item ) {
    this.transferPropsTo( item );
}, this);

Problem:

Failed to make request: Error: Invariant Violation: exports: You can't call
transferPropsTo() on a component that you don't own, exports. This usually
means you are calling transferPropsTo() on a component passed in as props
or children.

Bad solution #1: Use react-addons.js cloneWithProps method to clone the children at render time in RadioGroup to be able to pass them properties

Bad solution #2: Implement an abstraction around HTML / JSX so that I can pass in the properties dynamically (kill me):

<RadioGroup items=[
    { type: Button, title: 'A' },
    { type: Button, title: 'B' }
]; />

And then in RadioGroup dynamically build these buttons.

This question doesn't help me because I need to render my children without knowing what they are


Solution 1:

I am not sure why you say that using cloneWithProps is a bad solution, but here is a working example using it.

var Hello = React.createClass({
    render: function() {
        return <div>Hello {this.props.name}</div>;
    }
});

var App = React.createClass({
    render: function() {
        return (
            <Group ref="buttonGroup">
                <Button key={1} name="Component A"/>
                <Button key={2} name="Component B"/>
                <Button key={3} name="Component C"/>
            </Group>
        );
    }
});

var Group = React.createClass({
    getInitialState: function() {
        return {
            selectedItem: null
        };
    },

    selectItem: function(item) {
        this.setState({
            selectedItem: item
        });
    },

    render: function() {
        var selectedKey = (this.state.selectedItem && this.state.selectedItem.props.key) || null;
        var children = this.props.children.map(function(item, i) {
            var isSelected = item.props.key === selectedKey;
            return React.addons.cloneWithProps(item, {
                isSelected: isSelected,
                selectItem: this.selectItem,
                key: item.props.key
            });
        }, this);

        return (
            <div>
                <strong>Selected:</strong> {this.state.selectedItem ? this.state.selectedItem.props.name : 'None'}
                <hr/>
                {children}
            </div>
        );
    }

});

var Button = React.createClass({
    handleClick: function() {
        this.props.selectItem(this);
    },

    render: function() {
        var selected = this.props.isSelected;
        return (
            <div
                onClick={this.handleClick}
                className={selected ? "selected" : ""}
            >
                {this.props.name} ({this.props.key}) {selected ? "<---" : ""}
            </div>
        );
    }

});


React.renderComponent(<App />, document.body);

Here's a jsFiddle showing it in action.

EDIT: here's a more complete example with dynamic tab content : jsFiddle

Solution 2:

The buttons should be stateless. Instead of updating a button's properties explicitly, just update the Group's own state and re-render. The Group's render method should then look at its state when rendering the buttons and pass "active" (or something) only to the active button.

Solution 3:

Maybe mine is a strange solution, but why do not use observer pattern?

RadioGroup.jsx

module.exports = React.createClass({
buttonSetters: [],
regSetter: function(v){
   buttonSetters.push(v);
},
handleChange: function(e) {
   // ...
   var name = e.target.name; //or name
   this.buttonSetters.forEach(function(v){
      if(v.name != name) v.setState(false);
   });
},
render: function() {
  return (
    <div>
      <Button title="A" regSetter={this.regSetter} onChange={handleChange}/>
      <Button title="B" regSetter={this.regSetter} onChange={handleChange} />
    </div>
  );
});

Button.jsx

module.exports = React.createClass({

    onChange: function( e ) {
        // How to modify children properties here???
    },
    componentDidMount: function() {
         this.props.regSetter({name:this.props.title,setState:this.setState});
    },
    onChange:function() {
         this.props.onChange();
    },
    render: function() {
        return (<div onChange={this.onChange}>
            <input element .../>
        </div>);
    }

});

maybe you require something else, but I found this very powerfull,

I really prefer to use an outer model that provide observer register methods for various tasks