In the world of React, a potent superpower that sets it apart as an exceptional framework is its feature known as "props," short for properties. Props provide a mechanism to convey data within components, facilitating the customization of both behavior and appearance. This seemingly simple concept forms the backbone of creating reusable components, thus enabling the development of powerful and dynamic web applications.
So, What Exactly are Props?
Props, or properties, are objects designed to pass data from one component to another, often from parent components to their child components. This mechanism allows us to change a component's behavior or appearance without needing to meddle with its internal workings. One crucial aspect to note is that props are strictly read-only; components that receive props cannot alter them directly.
The Magic of Passing Props
In React, the process of passing props involves a straightforward approach. Just as you assign attributes to HTML elements, you can bestow data upon a component by using attributes termed as props. For instance:
This is a simple card component we have created using typescript and tailwind for styling, that display the name and age of a person,
Let's consider a use case where we need to display the names and ages of more than 5 people. Instead of duplicating the same component code, we can utilize a single component called "ChildComponent" and pass in the necessary data using props.
By implementing props, we can achieve this in a clean and concise manner. Here's how
Now let's explain our code:
Looking at the code deeply we'd understand that the code is almost the same as the one earlier but with a little adjustments.
Adjustment 1: On line 7, the variable name is enclosed within curly braces {}. Similarly, on line 8, the variable age is also enclosed within curly braces. This signifies that these values are dynamic and can vary based on what is provided when the component is used.
Adjustment 2: Notably, our updated code now incorporates parameters on line 3. These parameters serve as placeholders for dynamic values. As a result, when utilizing the component, it is necessary to assign specific values to these parameters. The presence of TypeScript also helps further clarifies the expected data types that should be supplied, which in our case are string and number.
Now let's use our component
Now as we can see we are rendering our ChildComponent
in the parent component, where every person is reusing the same component but with their own name and age.
Output:
To make our code implementation a lot more better, we can then introduce the ES6 Map array method.
There you have it, this is a simple explanation to how react props work.
I hope this helps
Good luck
Top comments (0)