Render Props
19 January, 2023
0
0
0
Contributors
What is the render-props pattern?
The render props pattern in React is a way to share component logic between components. Instead of using traditional component inheritance, the render props pattern uses a technique called "prop drilling" to pass a function from a parent component to a child component. The child component then uses this function to render its content.
This allows the child component to have access to the same logic as the parent component, without having to inherit from the parent component. This pattern can help keep components more modular and reusable.
Example of render-props pattern
Here's an example of the render props pattern in a functional React component:
// Parent component that uses the render props pattern
function ParentComponent(props) {
const [data, setData] = useState([]);
function fetchData() {
// Make an API call to fetch data
// ...
setData(response);
}
return (
<div>
<button onClick={fetchData}>Fetch Data</button>
{/* Pass a function to the child component as a prop */}
<ChildComponent render={data => <div>{data}</div>} />
</div>
);
}
// Child component that uses the render prop
function ChildComponent(props) {
return <div>{props.render(props.data)}</div>;
}
In this example, the ParentComponent
has a state variable data
and a function fetchData
that retrieves data from an API. The ParentComponent
then renders a button and a ChildComponent
. The ChildComponent
receives a render
prop, which is a function that takes the data
and renders it.
When the button is clicked, the fetchData
function is called, and the data
is updated in the state. The ParentComponent
then passes the updated data
to the ChildComponent
as a prop. The ChildComponent
uses the render
prop to render the data
.
Summary
In this way, the ParentComponent
is responsible for fetching and managing the data
, while the ChildComponent
is responsible for rendering the data
. The ChildComponent
is reusable and can be used with any data that can be passed to the render
prop.