Seven patterns by example: The many ways to type="radio" in React
Originally published on the commercetools tech blog on 20 December 2017. Restored from the Internet Archive.
A guided tour through seven patterns in React explaining different ways of implementing a radio group as a React component. It will cover patterns such as: compound components, context, prop getters, render props and *Function as a Child *(FaaC). But first let us take a step back by discussing the problem we are trying to solve.
What is type="radio" and why should we “re-implement” it in React
An <input> element of type radio is often used as a **radio group **which, as the name implies, groups related options. Radio groups should be used when only one **option **can be selected at the same time by a user. An example would be selecting the size of a T-Shirt of either M, L or XL.
Implementing these in React without wrapping them into a component is fairly straight forward. In its simplest form it could look something as this:
The example is implemented as a controlled component which means nothing more than that the size data is handled by a React component rendering the input while the input has a change handler to notify our React component about changes. To solve the problem above we would render three of these inputs each with a different value. There are however already some downsides to this approach:
- **Leaky abstraction: **
onChangepasses an[event](https://reactjs.org/docs/events.html)tohandleChangefrom which we need to extract thevalue(fromevent.target.value) - **Not DRY: **ensuring that
checkedis correctly set we have to repeat the comparison ofpropsand thevalueon each input field itself which is error prone and might break easily - **Not accessible: **each
inputshould be wrapped by alabelor have an adjacentlabelwith aforprop. Thislabelshould also be clickable for the user also triggering theRadioOption. This should abstracted away ensuring we always have alabeland users of ourRadioOptiondo not have to worry about it. It is worth mentioning that the same applied toaria-roles. However, these are are out of scope for this article. Lastly, theinputlikely needs some custom styling to fit into the corporate identity of the project. This can be achieved by one or moreclassNames supported by for instance[classnames](https://github.com/JedWatson/classnames). However, this will also be repetitive when using theinputand when forgotten or changed leads to inconsistent UI. With all that in mind we can for instance imagine ourinputsneeding the following look:
With the requirements and problems being defined, lets finally jump into some code which will build up different proposed solutions.
Solution 1: Defining RadioGroup and an options argument
We can solve most of the goals stated above by defining a RadioGroup which receives an options argument. You would then use this argument to pass the complete configuration for all the RadioGroups as a complex data-structure. The options would be of type array and should contain a value and an label to distinguish between the visual representation and the actual value of each option. This method is quite widely used as for instance in [react-select](https://github.com/JedWatson/react-select) and would look as follows:
The responsibility of the RadioGroup is to render an input per passed option while computing and forwarding the provided prop to the inputs. Lets look how this solves our problems in more detail:
-
The
RadioGroupcan internally pass down an improvedonChangeto the underlyinginputextracting thevaluefrom theevent -
The
RadioGroupcan contain some custom styling through e.g. CSS and custom SVGs and abstract those away -
The
RadioGroupcan passcheckedto theinputcomparingvalueandoption[n].valueEven though this already feels like a good solution already we can still improve our component to solve some of the following previously unthought of issues: -
Improve the declarative nature of our component (one of React’s strengths) by defining what we want to render not through an
optionsargument -
Slightly improve performance of the application as
optionswill have a new reference on each render triggering an wasteful render (for completeness: we can also use memoization or an immutable data structure for this) -
Enable to potentially influence how the actual
inputsare rendered to e.g. change their layout With these in mind we can continue to our next solution.
Solution 2: Defining RadioGroup and RadioOption components
We can continue tackling more of the discovered and newly created problems by abstracting the input into an RadioOption being wrapped by anRadioGroup . The latter will start to show its to more clearly show its advantages a bit later. The envisioned way to declare a group of radios would be:
This nicely iterates on our newly found problems of our previous solution:
- We declaratively render
RadioOptionsas child-elements of RadioGroup defining the intended state of our view - We will not trigger wasteful renders by passing in referentially different
options - We can use any kind of layout (e.g. custom
div) component in between or around theRadioOptions - The
RadioOptioncan still pass down an improvedonChangeto itsinput - The
RadioOptioncan still contain custom styling - The
RadioOptionalso passescheckedto theinputcomparingvalueandselectedValueHowever, we can still do better and remove for instance the need to specify theselectedValueandonChangeon eachRadioOption.
Solution 3: Compound components through RadioGroup
Compound components are a pattern in React in which the given children are re-assembled by providing or injecting custom props which the parent (in our case RadioGroup) is able to compute and provide. Using this pattern eases the usage of our RadioGroup and RadioOption to the following:
So how do the props from RadioGroup end up in RadioOption and ultimately in the input elements? Through React’s Top-Level API which has functions such as React.children.map and cloneElement. For a more profound deep dive of these and other functions please also head to “A deep dive into children in React”.
In our specific case we would map over the children checking their type to be of RadioOption to cloneElement each providing the additional props.
Note that for the given example the RadioGroup will likely be an React.Component we just wanted to keep things short for the code sample. Anyway, this pattern is able to solve all of our problems stated above. It is declarative, encapsulates styling, is performant and serves a good and concise API to consumers of RadioGroup and RadioOptions.
There are however some downsides with it:
- Prop-type validation happens at element creation time to produce more useful errors. However, we
cloneElementtheRadioOptionalready implying that it has been created before. This results in the fact that we can not mark any of the compound props fromRadioOptionasisRequired - Direct child: means that each
RadioOptionhas to be a direct child ofRadioGroup. We can not have any wrapping components around aRadioOption. The latter might be a bit of an “artificial” problem and also a good constraint to consumers of our component. However,[react-call-return](https://github.com/facebook/react/tree/master/packages/react-call-return)plans to solve this problem. Allowing a more natural composition of components in future versions of React. Until then we can, if needed, resort to another solution.
Solution 4: A shared context for RadioGroup and RadioOption
In general context enables us to build an API where parents and children can communicate across other component’s boundaries. Without going into too much detail: using context is a bit controversial in general. It might change with an RFC in process. A good guide to when to use it is laid out in an older Tweet by Dan Abramov. Assuming that we are sure to use context we would:
In this example RadioGroup functions as a provider for the context while RadioOption is a consumer. This replaces the need for cloneElement as the RadioGroup has to manually wire itself up by reading the respective values of the context. As a result, using context decouples RadioGroup and RadioOption as expected allowing nesting and intermediary components in between the two. For a consumer of our two components not much changes as context is an implementation detail depending on the requirements we need to fulfil.
Using context also somewhat nicely solves our previously discovered problem with missing ability to perform rigorous prop-type checks with isRequired due to the cloneElement for compound components.
It should also be noted that it is advised to abstract the usage of context in the attempt to guard against potential breaking changes in its API. We can do so by e.g. using Higher Order Components (HoC) offered by [recompose](https://github.com/acdlite/recompose). Using [withContext](https://github.com/acdlite/recompose/blob/master/docs/API.md#withcontext) in RadioGroup to define the childContextTypes and getChildContext and [getContext](https://github.com/acdlite/recompose/blob/master/docs/API.md#getcontext) in RadioOption would allow us to achieve just that.
There is another major downside which is oftentimes forgotten when working with context in React. Whenever any of the intermediary components returns false from shouldComponentUpdate a change in any of the context values will not be propagated to the RadioOptions. Libraries such as [flopflip](https://github.com/tdeekens/flopflip) work around that constraint by using something like [react-broadcast](https://github.com/ReactTraining/react-broadcast) which essentially sets up an event broadcasting system through context.
Solution 5: RadioGroup with Function as a Child (FaaC)
Moving away from a controversial pattern, to allow for nesting, to a more “standard” way empowering this, we can explore the power of the Function as a Child pattern in React. As a result children of RadioGroup would become a function receiving arguments for the RadioOptions such as onChange, name and the value. With this explanation the code would roughly look as follows:
Apart from the attempt to be fancy and using [React.Fragment](https://reactjs.org/docs/fragments.html) this solution should show that we could use any other intermediary layout components between RadioGroup and RadioOption. We could also use a render prop instead of children or offer both. A decision which is up to the team to decide upon. Anyhow, there are some slight downsides with this, as with any, approach namely:
- Wiring up
RadioOptionsis left to the consumer of our component making the API a bit more noisy to work with - Without extracting
childrenonto some instance variable it will be referentially different toRadioGroupduring reconciliation triggering wasteful renders just asoptions - With increasing distance between
RadioGroupandRadioOptionand more nesting it might become unclear whereonChangecomes from. It might even yield silent errors by shadowing any of the props such asonChangewhich will break the component However, none of these stated problems are unsolvable which brings us to another possible solution.
Solution 6: RadioGroup with prop getters for RadioOption
Prop getters are a pattern in React which recently gained prominence but theoretically was possible for longer. Its use and visibility increased significantly with the release of [downshift](https://github.com/paypal/downshift). With it, we would pass down a prop getter from RadioGroup which would look like:
The example shows how all props are passed through the FaaC of RadioGroup to RadioOption and are contained in a simple function when invoked returning the needed props for the RadioOption. This pattern quite significantly decreases the amount of manual wiring we had to carry out in the previous solution. Often the prop getter itself accepts additional arguments which influence its returned props. We could for instance pass in a related prop such as className which would look like getOptionProps({ className: 'custom' }).
This serves already as a quite concise and nice way to implement both RadioGroup and RadioOption. There is however another pattern to explore.
Solution 7: RadioGroup dynamically creates RadioOption
This might be the most rarely seen solution which might make it seem a bit exotic. We add a little twist to the previously mentioned compound component pattern by mixing it with the FaaC solution. This gives us a RadioGroup which passes down “patched” RadioOptions through its children prop. It would look something like:
This gives us the ability to nest just as with our context and FaaC based solutions without imposing any of their stated problems. The pattern has been discussed in a tweet and is also used within an older version or [react-radio-group](https://github.com/chenglou/react-radio-group/tree/9a992f3bbc1bffeb1dc993e42b0f4842ab299f42). It mixes both the FaaC and compound component patterns to an extend where the RadioOption is dynamically assembled in the RadioGroup for use in the children function only needing the value.
Coming to an end
I hope you enjoyed the little walk through different ways of implementing an good old type="radio" in React. I am sure there are even more ways of going about things. It is important to keep in mind that none of the outlined solutions is meant to be the best or goto approach. All seven seven different approaches come with their own set of advantages and disadvantages which should be contrasted with the given requirements. More importantly all patterns do not only apply to radio buttons but to almost any component you might be building in the future.
We at commercetools went with the compound component solution for know while accepting a vertical or horizontal layout prop on the RadioGroup to work around the nesting and requirement for different layouts options.