Thoughts and Notes on Software Development

Passing Functions to Child Component in React

In the parent React class component, you can declare a function, that you can then pass into one of its child components.

So say you had a <Form /> child component and a addNewProfile function. You can pass the function to the child component like so:

<Form onSubmit={this.addNewProfile} />

Then in the code for the Form component, you can get to the passed in function via the props object, like so:

 this.props.onSubmit(/*parameters go in here*/)

Note how React is smart enough to know that there would be an onSubmit property available in this.props. That's one of the cool things with React props.

So anyway, passing functions into child components is basically like passing a reference to a function. It's similar to how delegates work in C# and .NET.

Tags: #ReactJS

Discuss... or leave a comment below.