React Props

ReactBeginner
Practice Now

Introduction

In React, props (short for "properties") are a fundamental concept for passing data from one component to another. They allow you to create dynamic and reusable components. Think of props as arguments you pass to a function; they let a parent component configure its child components. Props are read-only, meaning a child component should never modify the props it receives.

In this lab, you will learn how to:

  • Define and pass props from a parent component to a child component.
  • Access and use props within a child component.
  • Use destructuring to make your code cleaner.
  • Set default values for props.

Let's get started!

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 91% completion rate. It has received a 100% positive review rate from learners.

Define props parameter in functional component

In this step, you will create a new child component and prepare it to receive props. Functional components in React can accept a single argument, which is an object containing all the props passed to it. By convention, this object is named props.

First, let's navigate to our project directory. The setup script has already created a project named my-app.

cd ~/project/my-app

Next, we need to install the project dependencies.

npm install

Now, let's create a new component file. In the file explorer on the left, navigate to the src folder. Create a new file inside src and name it Greeting.jsx.

Add the following code to your newly created src/Greeting.jsx file. This defines a simple functional component that accepts a props parameter.

function Greeting(props) {
  return <h2>Hello, World!</h2>;
}

export default Greeting;

Next, we need to import and use this new component in our main App component. Open the src/App.jsx file and modify it to look like this:

import Greeting from "./Greeting.jsx";

function App() {
  return (
    <>
      <h1>Welcome to My App</h1>
      <Greeting />
    </>
  );
}

export default App;

Now, let's start the development server to see our application.

npm run dev -- --host 0.0.0.0 --port 8080

After running the command, switch to the Web 8080 tab in the top-left corner of the interface. You should see your application running, displaying "Welcome to My App" and "Hello, World!".

Pass prop value from parent like name="John"

In this step, you will learn how to pass data from the parent component (App) to the child component (Greeting). This is done using an attribute-like syntax in JSX.

We want to pass a person's name to our Greeting component so it can display a personalized message.

Open the src/App.jsx file. Modify the <Greeting /> line to include a name prop with a value of "John".

import Greeting from "./Greeting.jsx";

function App() {
  return (
    <>
      <h1>Welcome to My App</h1>
      <Greeting name="John" />
    </>
  );
}

export default App;

Here, name="John" is the prop. name is the prop's key, and "John" is its value. You can pass any JavaScript expression as a prop value by wrapping it in curly braces {}. For strings, quotes are sufficient.

After saving the file, the development server will automatically reload. If you check the Web 8080 tab, the output will not have changed yet. This is because we have passed the prop, but the Greeting component is not yet using it. We will fix that in the next step.

Access prop in child with props.name

Now that the Greeting component is receiving the name prop, let's use it. The props object in the child component contains all the properties passed from the parent. You can access them using dot notation, like props.propertyName.

Open the src/Greeting.jsx file. We will modify it to access props.name and display the personalized greeting. Use curly braces {} to embed the JavaScript expression directly into your JSX.

Update src/Greeting.jsx with the following code:

function Greeting(props) {
  return <h2>Hello, {props.name}!</h2>;
}

export default Greeting;

Save the file. Now, switch to the Web 8080 tab. You should see the message has updated to "Hello, John!".

This demonstrates the basic flow of data in React: from parent to child via props.

Destructure props in function parameter

Writing props.name, props.age, etc., can become repetitive, especially if a component receives many props. A cleaner and more common approach is to use ES6 destructuring to unpack the properties from the props object directly in the function's parameter list.

Let's refactor the Greeting component to use destructuring.

Open src/Greeting.jsx and modify the function signature. Instead of accepting props, we will destructure it to get name directly.

Update the file to look like this:

function Greeting({ name }) {
  return <h2>Hello, {name}!</h2>;
}

export default Greeting;

By changing (props) to ({ name }), we are telling JavaScript to extract the name property from the object passed to the function. This makes the component's body cleaner, as we can now use name directly instead of props.name.

Save the file and check the Web 8080 tab. The output should be exactly the same ("Hello, John!"), but our code is now more concise and readable.

Set default props with default parameter

What happens if a parent component doesn't pass a required prop? The value will be undefined, which can lead to errors or unexpected UI. To prevent this, you can specify default values for props.

For functional components, you can use default parameters in the function signature.

Let's set a default name for our Greeting component. Open src/Greeting.jsx and modify the function parameter to include a default value. We'll set the default name to "Guest".

function Greeting({ name = "Guest" }) {
  return <h2>Hello, {name}!</h2>;
}

export default Greeting;

Now, let's test this. Open src/App.jsx and add another <Greeting /> component, but this time, do not pass a name prop to it.

import Greeting from "./Greeting.jsx";

function App() {
  return (
    <>
      <h1>Welcome to My App</h1>
      <Greeting name="John" />
      <Greeting />
    </>
  );
}

export default App;

Save both files. Go to the Web 8080 tab. You should now see two greetings:

  • "Hello, John!" (from the component that received the prop)
  • "Hello, Guest!" (from the component that used the default prop)

This is a robust way to make your components more predictable and prevent errors.

Summary

Congratulations on completing the lab! You have learned the fundamentals of using props in React to create reusable and dynamic components.

In this lab, you practiced:

  • Passing data from a parent component to a child component using props.
  • Accessing props within a child component using the props object.
  • Using destructuring to write cleaner, more readable code.
  • Setting default values for props with defaultProps to make your components more robust.

Props are a cornerstone of React development, and mastering them is a key step in building complex applications. Keep practicing these concepts as you continue your journey with React.