Unable to access function from parent - sending props from parent to child
I have an app which has a navbar, and a display below that shows all the posts.
Here is how it is setup:
var routes = (
<Router history={createHistory()}>
<Route path="/" component={App}>
<Route path="/submit" component={CreatePost}/>
</Route>
<Route path="*" component={NotExist}/>
</Router>
)
So, if you click on "New" in the navbar, you will be taken to server/submit
and a form will appear where you can enter details for a new post. On submit, it will add the details to the posts state object.
Inside of App, I have a function called addToPosts().
render : function() {
//<CreatePost addPostToPosts={this.addPostToPosts} posts={this.state.posts}/>
return (
<div>
<NavigationBar/>
{this.props.children}
<DisplayPosts postData={this.state.posts} />
</div>
)
}
@kirill-fuchs yesterday told me to use {this.props.children} to send the properties. However, when I check react console, I see that props are empty. But, I know it is doing something because if I get rid of the {this.props.children} then clicking on New doesn't do anything. But when I put it back, it redirects to the form.
In addition, when I click submit in the form, it says this.props.addToPosts is not a function, because the props are empty.
Can someone please help me?
Answer
It sounds like you want to pass props down to the children. You can use the following to do that:
{React.cloneElement(this.props.children, {addToPosts: this.addPostToPosts, posts: this.state.posts})}
This will pass a prop into the CreatePost
component that you can then call when the submit button is pressed.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM