Ram Mudaliar
Ram Mudaliar

Reputation: 541

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?

Upvotes: 1

Views: 33

Answers (1)

Tim Banks
Tim Banks

Reputation: 7179

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.

Upvotes: 1

Related Questions