Passing State as Props
In React, state can be passed between components using props. This allows a child component to access and use the state values of its parent component.
To pass state as props, follow these steps:
- Define the state in the parent component
- Render the child component and pass the state value as a prop
- Access the state value in the child component using props
Here's an example:
SNIPPET
1// Let's create a parent component that has a state value
2import React, { useState } from 'react';
3
4const ParentComponent = () => {
5 const [count, setCount] = useState(0);
6
7 return (
8 <div>
9 <h1>Parent Component</h1>
10 <p>Count: {count}</p>
11 <ChildComponent count={count} />
12 </div>
13 );
14};
15
16// Now, let's create a child component that receives the state value as a prop
17const ChildComponent = ({ count }) => {
18 return (
19 <div>
20 <h2>Child Component</h2>
21 <p>Received Count: {count}</p>
22 </div>
23 );
24};
25
26const App = () => {
27 return (
28 <div>
29 <ParentComponent />
30 </div>
31 );
32};
33
34ReactDOM.render(<App />, document.getElementById('root'));
In this example, the ParentComponent
has a state value count
initialized to 0. The count
value is passed as a prop to the ChildComponent
using the count={count}
syntax. The ChildComponent
receives the prop value and displays it in the UI.
You can try running this code and see how the state value is passed as a prop and displayed in the child component.
xxxxxxxxxx
34
ReactDOM.render(<App />, document.getElementById('root'));
// Let's create a parent component that has a state value
import React, { useState } from 'react';
const ParentComponent = () => {
const [count, setCount] = useState(0);
return (
<div>
<h1>Parent Component</h1>
<p>Count: {count}</p>
<ChildComponent count={count} />
</div>
);
};
// Now, let's create a child component that receives the state value as a prop
const ChildComponent = ({ count }) => {
return (
<div>
<h2>Child Component</h2>
<p>Received Count: {count}</p>
</div>
);
};
const App = () => {
return (
<div>
<ParentComponent />
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment