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>
);
}
});
With react-router, you pass state or data from one component to another component to use the react-router Link component. Data pass more quickly in the new version of react-router (v6). For example, you can pass an object's data into one component to another component.
We have seen several examples and use cases in react router. One among them is passing props to the route component directly. Its very easy to achieve in react router, Lets create a new route for passing props to the component.
Sending state/props to another component using the onClick event: So first we store the state/props into the parent component i.e in which component where we trigger the onClick event. Then to pass the state into another component, we simply pass it as a prop.
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>
);
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With