How we use React “Render props” at Geckoboard
I first heard the term “Render props” in 2016 when I attended a React Training event here in London, run by Michael Jackson. At first I didn’t understand why it was helpful but, in the years since then, I have found the pattern useful in so many cases. Everyone seems to be talking about Render props at the moment so I thought I’d share some real components from our codebase at Geckoboard to illustrate how we use it.
I’m not going to cover what the Render props pattern is in this article because there are tons of great articles that explain that already. If you would like to learn more, I recommend watching Michael’s excellent conference talk about HOCs and Render props.
1. Feature Flagging
We often use feature flags to test new, experimental features and to ship those features to a limited set of customers. Our
<FeatureFlag /> component allows us to conditionally render UI based on the customer’s feature flags.
We store the feature flags in a Redux store, internally this component acts like a Redux connector that passes the flags to its children but, by taking a function as a child, it makes our JSX nice and readable.
2. Drag and Drop
The Geckoboard UI allows you to drag and drop “widgets” around a “dashboard”. Our
<DraggableWidget /> component wraps up all the logic for sensing drag events and updating the widget’s position relative to the dashboard. This way our widget component can focus purely on rendering its content.
3. Full-screen events
People want to display their Geckoboards on a TV Screen without having the browser toolbar visible. Luckily, all good browsers offer some full-screen functionality to make that possible. Our
<Fullscreen /> component lets its child know if the browser is currently in full-screen mode and offers two functions it can call to enter and exit full-screen.
We have one of these wrapping our dashboard container component so that it can display itself differently in full-screen mode (In full-screen we scale the dashboard to fill the screen and show a footer containing the dashboard title, a company logo and a clock). We have another wrapping the full-screen button, as shown in the example above, so the customer can toggle full-screen mode on and off.
Under the hood we use the fscreen library to make our full-screen functionality behave cross-browser.
These are three examples in a growing list of Render prop components we use in production at Geckoboard. Render props are a great way of extracting complexity into self-contained components, that you can use throughout your React codebase, while maintaining clean, readable JSX.
I hope this post gives you some inspiration for how to use the Render props pattern. Feel free to post your components in the comments, we’d be interested in seeing them!