Render Props
Render props is a design pattern in React where components’ logic is encapsulated in a prop that a component calls to render its output.
Let’s consider an example below:
import React from 'react';
import ToggleableContent from './components/toggleable-content';
const App = () => {
return (
<div>
<h1>Render Props</h1>
<ToggleableContent />
</div>
);
}
export default App;
Toggleable Component
import { useState } from 'react';
const ToggleableContent = () => {
const [isOpen, setIsOpen] = useState(false);
const toggle = () => {
setIsOpen(!isOpen);
};
return (
<div>
<button onClick={toggle}>{isOpen ? "Hide" : "Show"} Content</button>
{isOpen && <p>Hello World!</p>}
</div>
);
};
export default ToggleableContent;
Now imagine a scenario where we have to reuse this component again and again.
import React from 'react';
import ToggleableContent from './components/toggleable-content';
const App = () => {
return (
<div>
<h1>Render Props</h1>
<ToggleableContent
render={({isOpen, toggle}) => {
return (
<div>
<button onClick={toggle}>{isOpen ? "Hide" : "Show"} Content
</button>
{isOpen && <p>Hello World!</p>}
</div>
);
}};
/>
</div>
);
};
export default App;
import { useState } from 'react';
const ToggleableContent = (render) => {
const [isOpen, setIsOpen] = useState(false);
const toggle = () => {
setIsOpen(!isOpen);
};
return (
render({isOpen, toggle});
);
};
export default ToggleableContent;
The above is a small yet powerful use case which can help you achieve more flexibility while reusing your components!