Reuse Your Components With Props

You’ll have understood by now that reusing components is at the very heart of React’s logic. However, to be reused, components often require configuration, which is where props come in. 🄳

Discover the PropsĀ Syntax

Do you realize that you've already used a prop? That’s right – the Ā keyĀ  prop in the chapter on lists! So you’ve seen the syntax.

Let’s go back to our plant site. We’re now going to create a new component that we’ll reuse. The idea is to create a water scale and a light scale for each plant.

We’ll reopen Ā ShoppingList.jsĀ andĀ add the relevant data in Ā plantList:Ā 

  • waterĀ  data, which corresponds to the recommended amount of water for each plant.

  • lightĀ  data, which corresponds to the amount of light required.

Starting with light, in each plant item, add a Ā CareScaleĀ  component to which we’ll pass the value prop:

<CareScale scaleValue={plant.light} />

Ā But hold on, how do we get the value of a prop into our component?Ā 

Ā You get props from the parameters of the function that defines your component.Ā 

So, for Ā CareScaleĀ ,Ā you have:

function CareScale(props) {
    const scaleValue = props.value
    return <div>{scaleValue}ā˜€ļø</div>
}

export default CareScale

But didn’t we say we wanted a scale from 1 to 3?

To do this, go for a list, which you can create manually.

YouĀ end up with:

function CareScale(props) {
    const scaleValue = props.value

    const range = [1, 2, 3]

    return (
        <div>
            {range.map((rangeElem) =>
                scaleValue >= rangeElem ? <span key={rangeElem.toString()}>ā˜€ļø</span> : null
            )}
        </div>
    )
}

Congratulations! You’ve just used props!

Props areĀ objects that you get from the parameters of your function component.Ā Ā 

Let’s take this concept a bit further to configure our component fully.

Create Parameters

Start by specifying aĀ Ā typeĀ  Ā propĀ  for theĀ Ā CareScaleĀ component and then reuse this component for both water and light:

<CareScale careType='water' scaleValue={plant.water} />
<CareScale careType='light' scaleValue={plant.light} />

Now adapt the Ā CareScaleĀ  to get the Ā careTypeĀ  .Ā 

We can now configure theĀ  CareScaleĀ  component so it can generate the data for water and light:

function CareScale({ scaleValue, careType }) {
    const range = [1, 2, 3]
    
    const scaleType = careType === 'light' ? 'ā˜€ļø' : 'šŸ’§'
    
    return (
        <div>
            {range.map((rangeElem) => scaleValue >= rangeElem ? <span key={rangeElem.toString()}>{scaleType}</span> : null
            )}
        </div>
    )
}

As you can see, we used two different syntaxes for our props. For Ā scaleTypeĀ  , we assigned a Ā stringĀ  between quotes. However, we gaveĀ Ā scaleValueĀ  the value of an object, which we passed between curly braces.Ā 

In practice, you can give a prop any possible value in JavaScript, but syntactically, in JSX, you only have two options:

  • AĀ Ā StringĀ  literal, marked by quotes.Ā 

  • Curly braces Ā {}Ā  for everything else (boolean, number, JavaScript expression, etc.).

Manage Data Flow From Parent to Child

So props allow you to configure your components. They respond to the React logic, according to which data descends through your tree of components in a one-way data flow.Ā Ā 

A diagram illustrating data flowing from a block labeled parent down to two blocks labeled child.
Parent components share their data with their children.

Did we mention parent and child components in the first part?

As you probably suspected, a component is the child of the component in which it was defined in the Ā return()Ā  .Ā 

In our example, Ā CareScaleĀ  Ā is the child, and Ā ShoppingListĀ  is the parent.Ā 

For props, there are two rules you have to follow:

  • A parent component always passesĀ a prop to its child: this is the only normal route of transmission.

  • A prop is read-only in the component that receives it.

Use the ChildrenĀ Technical Prop

Some React props behave in a slightly peculiar manner. These are calledĀ technical props.Ā 

The Ā childrenĀ  prop has slightly unusual syntax, as it is not provided using an attribute but rather by nesting components within the relevant component.Ā 

So you have:

<Parent>
    <Child1 />
    <Child2 />
</Parent>

For example, if youĀ use Ā childrenĀ  Ā to rewrite the Ā BannerĀ in Ā App.jsĀ , you get:

<Banner>
    <img src={logo} alt='Jungle House' />
    <h1 className='jh-title'>Jungle House</h1>
</Banner>

Here, Ā ImgĀ  and Ā h1Ā  are the child nodes in the Ā BannerĀ  DOM.Ā 

You can access these Ā BannerĀ  child nodes in the parameters, similar to the way you get props:Ā 

function Banner({ children }) {
    return <div className='jh-banner'>{children}</div>
}

This way of using Ā childrenĀ  is particularly useful when a component does not know its children in advance, e.g., on a sidebar or a modal.Ā 

To help with this, React has created PropTypes, which you can use to specify the type of prop from the very start, if required, and assign it a default value. We won’t study these in this course, so take a moment to look at them.Ā 

Give It a Go!

It’s time to use what you’ve learned to improve our plant shop site. 🌱 You can find the code for starting this exercise on branch P2C4-Begin.Ā 

Create a PlantItem component, which will be a child component ofĀ ShoppingList.

PlantItem takes the props:

  • nameĀ  for the plant name.

  • coverĀ  for the corresponding image.

  • idĀ , which corresponds to the item for each element.

  • lightĀ .

  • waterĀ .Ā 

The Ā nameĀ  and Ā coverĀ  will be used directly in PlantItem.

lightĀ  and Ā waterĀ  , which we have already created together, will be passed to the Ā CareScaleĀ  component in Ā PlantItemĀ  .Ā 

In Ā styles/PlantItem.cssĀ , you’ll find the CSS classes Ā jh-plant-item-coverĀ  and Ā jh-plant-itemĀ  , which will help you create good-looking components. Also, replace our emojis with the icons Ā sunĀ  and Ā waterĀ , which you can find in Ā /assetsĀ  .

Ā You’ll find the solution on branch P2C4-Solution.

Let’s Recap!

  • Props are objects thatĀ you can get from the parameters of your function component.Ā 

  • There are two syntaxes for assigning a value to a prop:Ā 

    • Quotes for Ā stringĀ  .

    • Curly braces for everything else (names, JavaScript expressions, booleans, etc.).

  • Destructuring is a syntax that you can use to declare a variable by giving it the value of an object (or array).

  • A prop is:Ā 

    • Always passed from parent to child component.Ā 

    • Read-only in the component that receives it.Ā 

  • The Ā childrenĀ  prop is entered by nesting children in the parent: <Parent><Child/></Parent>.

  • childrenĀ  is useful when a component doesn’t know its children in advance.Ā 

Our plant site is starting to take shape!Ā But don’t you think it’s all a bit static? There isn’t much opportunity for interaction, is there? No problem, because that’s what we’ll tackle in the next chapter. See you there!

Ever considered an OpenClassrooms diploma?
  • Up to 100% of your training program funded
  • Flexible start date
  • Career-focused projects
  • Individual mentoring
Find the training program and funding option that suits you best