How to pass both this.state and this.props to routes using react-router

I can’t figure out how to access a method from a parent ReactJS component within my post route and component. Using react-router.

This is in
<RouteHandler {...this.state} />

The method/function pushToPostList() in adds a post object to an array, held in this.state.myList.

Trying to get my <Post /> component working so it calls this.props.pushToPostList(newPost) to update this.state.myList in <App />

Router is:

var routes = (
  <Route handler={App} >
    <DefaultRoute handler={SignUp} />
    <Route name="feed" path="feed" handler={LatestFeed} />
    <Route name="post" path="post" handler={Post} pushToPostList={this.pushToPostList} />
  </Route>
);


Router.run(routes, function (Handler) {
  React.render(<Handler />, document.body );
});

More code:
var App = React.createClass({

    getInitialState: function() {
        return {
            myList: []
        };
    },

    pushToPostList: function (object) {
        if (object) { 
          var myTempPosts = this.state.myPostList;
          myTempPosts.push(object); 
          this.setState( {myPostList: myTempPosts} );
        }
    },

    render: function() {        
        return (
            <div>
                <RouteHandler {...this.state} />
            </div>
        );
    }
});


var Post = React.createClass({

    handleSubmit: function(e) {
        e.preventDefault();

        var myPostTxt = this.refs.myPostTxt.getDOMNode().value.trim();
        this.props.pushToPostList( myPostTxt ); // Send object to parent ReactJS component.

    },

    render: function() {
        return (
            <div>
                Post.

                <textarea 
                  ref="myPostTxt" />

                <p />
                <button onClick={this.handleSubmit} type="submit">Post</button>

            </div>
        );
    }
});

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Move pushToPostList={this.pushToPostList} to the App Class.

var App = React.createClass({

getInitialState: function() {
    return {
        myList: []
    };
},

pushToPostList: function (object) {
    if (object) { 
      var myTempPosts = this.state.myPostList;
      myTempPosts.push(object); 
      this.setState( {myPostList: myTempPosts} );
    }
},

render: function() {        
    return (
        <div>
            <RouteHandler {...this.state} pushToPostList={this.pushToPostList} />
        </div>
    );
}
});


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x