Goal of the tutorial: This tutorial aims to provide a comprehensive understanding of how to pass and manage props in React. Props are a way of passing data from parent components to child components in React.
What you'll learn:
Prerequisites: Basic understanding of React, JavaScript, and JSX.
In React, "props" is a special keyword that stands for properties. Props are used to pass data from one component to another. Particularly, they are always passed from parent component to child component.
To pass props to a child component, you add them as attributes when you use the child component inside the parent component.
<ChildComponent someProp={value} />
Inside the child component, you can access the props using this.props
in a class component or as an argument in a functional component.
function ChildComponent(props) {
return <p>{props.someProp}</p>;
}
// Parent Component
function ParentComponent() {
return <ChildComponent someProp="Hello, World!" />;
}
// Child Component
function ChildComponent(props) {
return <p>{props.someProp}</p>; // Outputs: Hello, World!
}
In the above example, "Hello, World!" is passed as a prop from ParentComponent
to ChildComponent
. Inside ChildComponent
, we access someProp
and render it inside a paragraph.
// Parent Component
function ParentComponent() {
return <ChildComponent prop1="Hello" prop2="World!" />;
}
// Child Component
function ChildComponent(props) {
return <p>{props.prop1} {props.prop2}</p>; // Outputs: Hello World!
}
Here, we pass two props from ParentComponent
to ChildComponent
. Both are accessed and rendered inside a paragraph.
In this tutorial, you've learned about props in React and how to pass and access them in child components. As a next step, you could learn about prop types and how to use them to validate the data being passed as props.
Create a ParentComponent
that passes a prop name
to a ChildComponent
. The ChildComponent
should render "Hello, name
!".
Create a ParentComponent
that passes two props firstName
and lastName
to a ChildComponent
. The ChildComponent
should render "Hello, firstName
lastName
!".
Solutions:
// Parent Component
function ParentComponent() {
return <ChildComponent name="John" />;
}
// Child Component
function ChildComponent(props) {
return <p>Hello, {props.name}!</p>; // Outputs: Hello, John!
}
2.
// Parent Component
function ParentComponent() {
return <ChildComponent firstName="John" lastName="Doe" />;
}
// Child Component
function ChildComponent(props) {
return <p>Hello, {props.firstName} {props.lastName}!</p>; // Outputs: Hello, John Doe!
}
Happy coding!