DEV Community

Cobbygraves
Cobbygraves

Posted on

Demystifying Props in React Components

This tutorial aims at two things about props.

  • The purpose of props in react component

  • How to use props in react component

First of all let understand the purpose of props in react components. Basically, props is a way of passing data from parent component to child component in a react application.

I believe that's simple and easy to understand and achieve since react is a one-way data flow library. ie. data is passed from parent to child.

Now, how do we pass data from child to parent in a react application if the need arises. The answer to the question above is simple, props.

To better understand my answer, let look at a scenario using the code below.

child component without clickchild component

parent component without stateparent component

Now if we consider the two component above, how do we then show the age of the child component inside the parent component ?.
This is what I mean by my previous question ie. How do we pass data from the child component to the parent component ?

The answer still remains as before ie. props. Let see how to accomplish that in our previous code examples.

child component with onclickchild component

parent component with stateparent component

Comparing the parent and child component, we can conclude that, to pass the age value from the child component to the parent component, react makes use of what I termed as "functional
props"
. This simply means a prop which is a function.

The age from the child component must be passed as an argument to the functional prop inside of the child component. This is what is happening in the child component with respect to the showAge functional prop.

As the age which is a state in the child component is passed as an argument to the showAge prop, it is then received inside the parent component through a function and then displayed in it JSX below.

I hope you learn a lot about props and how data is passed from parent to child and vice versa in react component

Top comments (0)