Composition

One of the biggest benefits of React is composability. I personally don’t know a framework that offers such an easy way to create and combine components. In this section we will explore a few composition techniques which proved to work well.

Let’s get a simple example. Let’s say that we have an application with a header and we want to place a navigation inside. We have three React components - App, Header and Navigation. They have to be nested into each other so we end up with the following dependencies:

  1. <App> -> <Header> -> <Navigation>

The trivial approach for combining these components is to reference them in the places where we need them.

  1. // app.jsx
  2. import Header from './Header.jsx';
  3. export default function App() {
  4. return <Header />;
  5. }
  6. // Header.jsx
  7. import Navigation from './Navigation.jsx';
  8. export default function Header() {
  9. return <header><Navigation /></header>;
  10. }
  11. // Navigation.jsx
  12. export default function Navigation() {
  13. return (<nav> ... </nav>);
  14. }

However, by following this approach we introduced a couple of problems:

  • We may consider the App as a place where we do our main composition. The Header though may have other elements like a logo, search field or a slogan. It will be nice if they are passed somehow from the App component so we don’t create hard-coded dependencies. What if we need the same Header component but without the Navigation. We can’t easily achieve that because we have the two bound tightly together.
  • It’s difficult to test. We may have some business logic in the Header and in order to test it we have to create an instance of the component. However, because it imports other components we will probably create instances of those components too and it becomes heavy to test. We may break our Header test by doing something wrong in the Navigation component which is totally misleading. (Note: to some extent shallow rendering solves this problem by rendering only the Header without its nested children.)

Using React’s children API

In React we have the handy children prop. That’s how the parent reads/accesses its children. This API will make our Header agnostic and dependency-free:

  1. export default function App() {
  2. return (
  3. <Header>
  4. <Navigation />
  5. </Header>
  6. );
  7. }
  8. export default function Header({ children }) {
  9. return <header>{ children }</header>;
  10. };

Notice also that if we don’t use { children } in Header, the Navigation component will never be rendered.

It now becomes easier to test because we may render the Header with an empty <div>. This will isolate the component and will let us focus on one piece of our application.

Passing a child as a prop

Every React component receives props. As we mentioned already there is no any strict rule about what these props are. We may even pass other components.

  1. const Title = function () {
  2. return <h1>Hello there!</h1>;
  3. }
  4. const Header = function ({ title, children }) {
  5. return (
  6. <header>
  7. { title }
  8. { children }
  9. </header>
  10. );
  11. }
  12. function App() {
  13. return (
  14. <Header title={ <Title /> }>
  15. <Navigation />
  16. </Header>
  17. );
  18. };

This technique is useful when a component like Header needs to take decisions about its children but don’t bother about what they actually are. A simple example is a visibility component that hides its children based on a specific condition.

Higher-order component

For a long period of time higher-order components were the most popular way to enhance and compose React elements. They look really similar to the decorator design pattern because we have component wrapping and enhancing.

On the technical side the higher-order component is usually a function that accepts our original component and returns an enhanced/populated version of it. The most trivial example is as follows:

  1. var enhanceComponent = (Component) =>
  2. class Enhance extends React.Component {
  3. render() {
  4. return (
  5. <Component {...this.props} />
  6. )
  7. }
  8. };
  9. var OriginalTitle = () => <h1>Hello world</h1>;
  10. var EnhancedTitle = enhanceComponent(OriginalTitle);
  11. class App extends React.Component {
  12. render() {
  13. return <EnhancedTitle />;
  14. }
  15. };

The very first thing that the higher-order component does is to render the original component. It’s a good practice to proxy pass the props to it. This way we will keep the input of our original component. And here comes the first big benefit of this pattern - because we control the input of the component we may send something that the component usually has no access to. Let’s say that we have a configuration setting that OriginalTitle needs:

  1. var config = require('path/to/configuration');
  2. var enhanceComponent = (Component) =>
  3. class Enhance extends React.Component {
  4. render() {
  5. return (
  6. <Component
  7. {...this.props}
  8. title={ config.appTitle }
  9. />
  10. )
  11. }
  12. };
  13. var OriginalTitle = ({ title }) => <h1>{ title }</h1>;
  14. var EnhancedTitle = enhanceComponent(OriginalTitle);

The knowledge for the appTitle is hidden into the higher-order component. OriginalTitle knows only that it receives a prop called title. It has no idea that this is coming from a configuration file. That’s a huge advantage because it allows us to isolate blocks. It also helps with the testing of the component because we can create mocks easily.

Another characteristic of this pattern is that we have a nice buffer for additional logic. For example, if our OriginalTitle needs data also from a remote server. We may query this data in the higher-order component and again send it as a prop.

  1. var enhanceComponent = (Component) =>
  2. class Enhance extends React.Component {
  3. constructor(props) {
  4. super(props);
  5. this.state = { remoteTitle: null };
  6. }
  7. componentDidMount() {
  8. fetchRemoteData('path/to/endpoint').then(data => {
  9. this.setState({ remoteTitle: data.title });
  10. });
  11. }
  12. render() {
  13. return (
  14. <Component
  15. {...this.props}
  16. title={ config.appTitle }
  17. remoteTitle={ this.state.remoteTitle }
  18. />
  19. )
  20. }
  21. };
  22. var OriginalTitle = ({ title, remoteTitle }) =>
  23. <h1>{ title }{ remoteTitle }</h1>;
  24. var EnhancedTitle = enhanceComponent(OriginalTitle);

Again, the OriginalTitle knows that it receives two props and has to render them next to each other. Its only concern is how the data looks like not where it comes from and how.

Dan Abramov made a really good point that the actual creation of the higher-order component (i.e. calling a function like enhanceComponent) should happen at a component definition level. Or in other words, it’s a bad practice to do it inside another React component because it may be slow and lead to performance issues.

Function as a children, render prop

For the last couple of months, the React community started shifting in an interesting direction. So far in our examples the children prop was a React component. There is however a new pattern gaining popularity in which the same children prop is a JSX expression. Let’s start by passing a simple object.

  1. function UserName({ children }) {
  2. return (
  3. <div>
  4. <b>{ children.lastName }</b>,
  5. { children.firstName }
  6. </div>
  7. );
  8. }
  9. function App() {
  10. const user = {
  11. firstName: 'Krasimir',
  12. lastName: 'Tsonev'
  13. };
  14. return (
  15. <UserName>{ user }</UserName>
  16. );
  17. }

This may look weird but in fact is really powerful. Like for example when we have some knowledge in the parent component and don’t necessary want to send it down to children. The example below prints a list of TODOs. The App component has all the data and knows how to determine whether a TODO is completed or not. The TodoList component simply encapsulate the needed HTML markup.

  1. function TodoList({ todos, children }) {
  2. return (
  3. <section className='main-section'>
  4. <ul className='todo-list'>{
  5. todos.map((todo, i) => (
  6. <li key={ i }>{ children(todo) }</li>
  7. ))
  8. }</ul>
  9. </section>
  10. );
  11. }
  12. function App() {
  13. const todos = [
  14. { label: 'Write tests', status: 'done' },
  15. { label: 'Sent report', status: 'progress' },
  16. { label: 'Answer emails', status: 'done' }
  17. ];
  18. const isCompleted = todo => todo.status === 'done';
  19. return (
  20. <TodoList todos={ todos }>
  21. {
  22. todo => isCompleted(todo) ?
  23. <b>{ todo.label }</b> :
  24. todo.label
  25. }
  26. </TodoList>
  27. );
  28. }

Notice how the App component doesn’t expose the structure of the data. TodoList has no idea that there is label or status properties.

The so called render prop pattern is almost the same except that we use the render prop and not children for rendering the todo.

  1. function TodoList({ todos, render }) {
  2. return (
  3. <section className='main-section'>
  4. <ul className='todo-list'>{
  5. todos.map((todo, i) => (
  6. <li key={ i }>{ render(todo) }</li>
  7. ))
  8. }</ul>
  9. </section>
  10. );
  11. }
  12. return (
  13. <TodoList
  14. todos={ todos }
  15. render={
  16. todo => isCompleted(todo) ?
  17. <b>{ todo.label }</b> : todo.label
  18. } />
  19. );

These two patterns, function as children and render prop are probably one of my favorite ones recently. They provide flexibility and help when we want to reuse code. They are also a powerful way to abstract imperative code.

  1. class DataProvider extends React.Component {
  2. constructor(props) {
  3. super(props);
  4. this.state = { data: null };
  5. setTimeout(() => this.setState({ data: 'Hey there!' }), 5000);
  6. }
  7. render() {
  8. if (this.state.data === null) return null;
  9. return (
  10. <section>{ this.props.render(this.state.data) }</section>
  11. );
  12. }
  13. }

DataProvider renders nothing when it first gets mounted. Five seconds later we update the state of the component and render a <section> followed by what is render prop returning. Imagine that this same component fetches data from a remote server and we want to display it only when it is available.

  1. <DataProvider render={ data => <p>The data is here!</p> } />

We do say what we want to happen but not how. That is hidden inside the DataProvider. These days we used this pattern at work where we had to restrict some UI to certain users having read:products permissions. And we used the render prop pattern.

  1. <Authorize
  2. permissionsInclude={[ 'read:products' ]}
  3. render={ () => <ProductsList /> } />

Pretty nice and self-explanatory in a declarative fashion. Authorize goes to our identity provider and checks what are the permissions of the current user. If he/she is allowed to read our products we render the ProductList.

Final thoughts

Did you wonder why HTML is still here. It was created in the dawn of the internet and we still use it. That is because it’s highly composable. React and its JSX looks like HTML on steroids and as such it comes with the same capabilities. So, make sure that you master the composition because that is one of the biggest benefits of React.