Laura Todd Codes

A Really Simple Intro to Using Props in React

A Really Simple Intro to Using Props in React

Props are an incredibly useful tool when working with React so it's worth spending some time getting used to them. Props are a way of sending data down the component tree from a parent to a child component.

I'll take you through a really simple example of using props to pass the users selection from a list of radio buttons to display in a child component.

Here's a screenshot of what we're looking to create - the selected name will display in the blue box, which is a child of the App component.

screenshot of desired result

Begin by setting up your form like this -

starting code for form

I've added some simple CSS too. You can find all of the starting code here .

If you haven't come across React.Fragment before, it's simply a way of wrapping your code without adding unnecessary div tags.

Now let's use the useState hook to initialise the state of 'value'. Then, create a function which sets the state of 'value' to the value of the selected radio button.

initialise state of value

Now we need to add the 'handleChange' function as an onChange event to the form.

add on change event

Next, let's create the child component in which we want to display our selected name. I've called the component 'Selection' but you can call it whatever you like. The 'Selection' component has a single pair of <h3> tags.

create Selection child component

Back in the App component, import 'Selection' and add it below your form.

import selection to app

Go back again to your 'Selection' file and add 'props' to the function parameters. This will allow you to pass down information from the parent component.

Then, within the <h3> tags add {props.selection}. You can can name the prop whatever you like but I have chosen to call it 'selection'.

add props.selection

Go back to the App component again and within the Selection component, add the 'selection' property (or whatever you've called it).

We can then assign {value} to it. You'll recall that value holds the state of the currently selected item. By assigning it to the 'selection' property, we have passed it down to the 'Selection' component and the chosen value will now display on the page.

add value to Selection component

You can check your finished code here .

Share this