Fowarding Props - anastasiamexa/react-complete-guide-course-resources GitHub Wiki
In React, "Fowarding Props" refers to the practice of passing props received by a parent component down to a child component without explicitly specifying each prop. This is especially useful when you want to maintain a clean and consistent interface for your component and avoid manually re-declaring all the props in the child component. Forwarding props can be accomplished using the ...
spread operator.
Here's an example to illustrate how forwarding props works in React:
function Section({ title, children, ...props }) {
return (
<section {...props}>
<h2>{title}</h2>
{children}
</section>
);
}
export default Section;
This component takes advantage of destructuring and the spread operator (...
) to handle props in a concise and flexible way.
Let's break down the code and understand its functionality:
1. Function Component Definition:
function Section({ title, children, ...props }) {
// ...
}
- The
Section
component is defined as a function component. - It receives three props:
title
,children
, and the rest of theprops
, which are collected into the props object using the spread operator (...props
).
2. Component Rendering:
return (
<section {...props}>
<h2>{title}</h2>
{children}
</section>
);
- Inside the component's return statement, it renders a
<section>
element with several properties. - The spread operator (
{...props}
) is used to pass all the additional props collected into theprops
object to the<section>
element. This allows you to add any custom attributes or properties to the<section>
element when using theSection
component. - It renders an
<h2>
element displaying thetitle
prop. - It renders the
children
prop, which is a special prop in React that represents the content enclosed within the component when it is used. This is typically used to render the content within the<Section>
component.
Here's how you might use this Section
component in another component or JSX:
import React from 'react';
import Section from './Section';
function App() {
return (
<div>
<Section title="Example Section" className="custom-section">
<p>This is the content of the section.</p>
</Section>
</div>
);
}
export default App;
In this example:
- We import the
Section
component. - We use the
Section
component, providing atitle
prop, aclassName
attribute, and some content (children
). - The
title
prop is used to set the section title. - The
className
attribute is added to the rendered<section>
element, thanks to the spread operator in theSection
component. - The content enclosed within the
Section
component (the<p>
element) is placed inside the{children}
placeholder in theSection
component.
Overall, this code demonstrates a flexible and reusable way to create sections with titles and additional properties, allowing you to customize each section's appearance and behavior as needed.