Render Props
Experienced Frontend Developer with a demonstrated history of working in the financial services industry along with having 5+ years of hands on professional experience efficiently coding websites and applications using modern HTML, CSS and Javascript along with their respective frameworks viz.Vue.JS, React.JS. Instituting new technologies and building easy to use and user-friendly websites is truly a passion of mine. I actively seek out new libraries and stay up-to-date on industry trends and advancements. Translated designs to frontend code along with streamlining existing code to improve site performance. Collaborated with UX designers and Back End Developers to ensure coherence between all parties. Also tested some feature prototypes for bugs and user experience.
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!