Using Props to Pass Data
One of the key concepts in React is props. Props (short for properties) allow you to pass data from a parent component to a child component.
Let's take a look at an example:
SNIPPET
1// Let's create a simple parent component
2
3function ParentComponent() {
4 const greeting = "Hello, World!";
5 return (
6 <div>
7 <ChildComponent greeting={greeting} />
8 </div>
9 );
10}
11
12// Now let's create the child component
13
14function ChildComponent(props) {
15 return (
16 <div>
17 <h2>{props.greeting}</h2>
18 <p>This is a child component.</p>
19 </div>
20 );
21}
22
23// In this example, the ParentComponent passes the greeting
24// value as a prop called 'greeting' to the ChildComponent.
25
26// The ChildComponent receives the prop and renders it in
27// a heading element. The prop can be accessed using the 'props'
28// parameter passed to the functional component.
29
30// This way, data can be passed from the parent component to
31// the child component using props.
In the code snippet above, we have a ParentComponent
that renders a ChildComponent
. The ParentComponent
has a variable called greeting
with the value "Hello, World!".
The greeting
value is passed to the ChildComponent
as a prop named greeting
.
Inside the ChildComponent
, the prop value is accessed using the props
parameter passed to the function. The prop is then rendered inside a heading element.
By using the props, we can pass data from the parent component to the child component and utilize it to render dynamic content or perform other operations.
xxxxxxxxxx
31
// the child component using props.
// Let's create a simple parent component
function ParentComponent() {
const greeting = "Hello, World!";
return (
<div>
<ChildComponent greeting={greeting} />
</div>
);
}
// Now let's create the child component
function ChildComponent(props) {
return (
<div>
<h2>{props.greeting}</h2>
<p>This is a child component.</p>
</div>
);
}
// In this example, the ParentComponent passes the greeting
// value as a prop called 'greeting' to the ChildComponent.
// The ChildComponent receives the prop and renders it in
// a heading element. The prop can be accessed using the 'props'
// parameter passed to the functional component.
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment