DEV Community

Cover image for A Really Simple Intro to Using Props in React
Laura Todd
Laura Todd

Posted on • Updated on

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.

final result

Begin by setting up your form like this -

JSX 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.

Add useState

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

Add handle change

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.

Add selection component

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

add Selection component 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

You can check your finished code here.

Top comments (0)