Ad

React JSX Spread Attribute In CloneElement

- 1 answer

I am learning React and got stuck. Maybe someone can help. I have the following code:

React-router

ReactDOM.render(

   <Router> 
       <Route path="/" component={App}>
           <Route path="something" component={Something} />
       </Route>
   </Router>

,document.getElementById('react-container')
);

App

var App = React.createClass({

getInitialState: function() {
    return {
        status: 'ready',
        title: 'The Title'
    }
},

render: function() {

    var childComp = null;

    if(this.props.children) {

            /*
                This will work 
                childComp = React.cloneElement(this.props.children, {title: this.state.title, status: this.state.status});
            */

            /*this wont*/
            childComp = React.cloneElement(this.props.children, {...this.state});
    }

    return (
        <div>
            <Header title={this.state.title} />
            {childComp}
        </div>
    );
}
});

Something:

var Something = React.createClass({
render: function() {
    return (
        <div>
            <h1>Something</h1>
            <h2>{this.props.title}</h2>
            <h3>{this.props.status}</h3>
        </div>
    );
}
});  

The problem is that App can have many many states. I dont want to manually write them like so:

React.cloneElement(this.props.children, {title: this.state.title, status: this.state.status})

But using JSX spread attributes wont work (syntaxerror)

Ad

Answer

React.cloneElement(this.props.children, this.state) should work.

Ad
source: stackoverflow.com
Ad