DEV Community

Cover image for Props
Amereen
Amereen

Posted on

Props

Data is passed from a parent component to a child component in React using props, which is short for properties. Similar to how HTML attributes are used to set the properties of an HTML element, props are supplied as attributes to the child component.
Here's an example of passing props to a child component:

Image description

In this example, the ParentComponent is passing a message prop with the value "Hello World" to the ChildComponent. The ChildComponent is then able to access the prop by destructuring the props object and extracting the message property. The child component then render the message prop into the div.
You can also pass multiple props to a child component, like this:

Image description
Here, the child component can access these props like this:

Image description

It's also possible to pass functions as props and allow the child component to interact with the parent component.

Image description

And then the child component can use it like this:

Image description

It's important to note that React follows one way data flow, meaning that data should flow from the parent component to child component and not the other way around. Thus, child component can't change the props passed to them, they can only use them to render or pass them to other child component.

When props are passed down to multiple levels of child components in a React application, it's often referred to as "prop drilling." This means that props are passed down through multiple levels of the component tree, from a parent component to a child component, and then from that child component to its own child component, and so on.

Here's an example of prop drilling:

Image description

In this example, the ParentComponent passes a message prop to the Child1 component. Child1 component then passes the same prop to its own child component Child2, which in turn passes the same prop to Child3. The Child3 component is then able to access the prop and use it to render the message.

Prop drilling can become tedious as the component tree grows and it becomes more difficult to trace where the props are being passed and how they are being used. In such cases, it's recommended to use context or higher-order component to avoid excessive prop drilling.

Top comments (0)