React Slots: a New Way of Composition


In this talk we will learn what is Slots and what does it mean to the React ecosystem, what's the current state and the future.



Hey, it's my great honor to be here to share with you some of my thoughts on design system. My name is Gongwu Nie, you can call me Nio. Today my topic is React Snots, a new way of composition. Before we dive into the topic, I'd like to tell the backstory first. When working on the design system, I'm always thinking how to build flexible and future-proof components. For me, the hardest thing is not creating new components or fixing weird bugs. It's the component API design. Every time when I found a new design system, the first thing I would do is to see how they implement the text input component, because it's one of the most mysterious components. Let me show you. Text input is simple and straightforward. It comes with a label, an input, and have a test. Let's add accessibility support first. When building a shareable component, please don't forget to forward ref. We need the ref to the input to focus it in form validation. But what about the wrapper? We also need the ref to the wrapper to attach propover or tutip to it in some cases. Well, we can add a wrapper for it. But wait, have you noticed a potential problem with this current approach? What will happen if we are trying to add some margins to the component from the other components? It will increase the margin between label, input, and description instead, because we spread all the rest prompts to the inner input element. The fix is simple. We can pass the class name and style to the component wrapper instead. Looks good? The problem is that the component is getting confusing for the consumers. Which prompts will be passed to the wrapper? Which prompts will be passed to the input? The component becomes a black box. In reality, the product teams will keep asking for more options to access the internal elements, like attaching point events or adding data attributes to the label or description, similar to wrapper ref. We can introduce wrapper prompts, label prompts, and description prompts. It works. But it doesn't end here. What if we need to add surroundings to the input? More prompts. Now you can see how API gets bloated with this approach. Here is the API of text input from Maintime. Don't get me wrong. Maintime is a great components library. I love it a lot. They choose the configuration way to design the component API. In the configuration way, we have to support flexibility with API bloating, and the components become a completely black box for the consumers. Let's take one step back and think. How do we build our web app in React? We compose components. Each component just does its own job and that's it. Simple and flexible. Then what if we use the same approach for shareable components? We gain the same clearance, simplicity, and flexibility. A lot of popular components libraries are using the composition way to implement accessible components like Chakra UI, Redux primitives, Hedonist UI, and more. To support accessibility, we have to use React context to communicate between parent and children to coordinate the accessibility attributes. Configuration is simple to use. You really want to write your model in the left style rather than the right style. But the composition way is not the final answer. Take the Chakra UI for example. What if we swap the position of input left addon and input right addon? We get input left addon shown on the right side and input right addon shown on the left side. It breaks semantic with a broken style. I have a hobby when I found a new design system is testing the resonance of components. By adding extra nodes to the items, we see how it breaks. For dedicated design systems, we deliver well-designed components. But you just can't imagine how alternative developers will break them in various ways. And unfortunately, we can't prevent them from doing that. You would say it doesn't matter if we follow the design order correctly. Okay, let's see a lot more realistic problem. Building an accessible list. The parent needs to know the children's information to make it accessibility compliant. For Azure Active Descendant, it's easy to achieve using the configuration way because the parent knows all the items from the item prompts. But it's a bit cumbersome for the composition way. The menu can't see its internal items. The component is blind. To solve the problem, we can use React Children with React Clone Element. Then we can take control of the rendering of items in parent component. But in terms of extension, it will break again. Even we can iterate the children, the parent is still blind, as it can't see the deep details. The problem is well described by rootUI. If you are interested, here I have a homework for you, figuring out how those libraries are trying to solve this problem. That's recap. The configuration way provides the best consistency, as the component is a single source of truth. But it's hard to extend, and it becomes a black box when multiple items are used. On the contrary, the composition way provides the best flexibility. You can customize your subcomponents freely. But it causes another problem, consistency. It needs uncontrolled use cases and wrong patterns. Then can we have a way to build components with flexibility while keeping the consistency? Yes, the answer is not. Slots is a standard for web components. In web components, slots are identified by their name attribute, and allow you to define placeholders in your template that can be filled with any mockup fragment you want when the element is used in the mockup. It's easier to understand the concept in code. First, we define a template with some named placeholders, and define the web component. Then we fill the named placeholders with named slots. Finally, we get the result with injected elements. Here you can see how the consistency is granted. The layout is defined in the template, not described by the composition order. Some popular frameworks like Vue and Svelte also implemented the slots composition pattern from framework level in a similar behavior. But as you know, React still doesn't support web components very well, not saying slots. There are a lot of approaches from the community trying to bring slots to React world. The most common way is using React-Children with React-Clone-Element, but it doesn't scale very well as component is blind that I just shown. React-Spectrum uses context and use grid order to solve the disorder problem, but the functionality is limited. For example, the grid order will change the type index in an unexpected way. GitHub Primer uses double rendering to approach slots. It renders the sub-components into a browser with empty content and gathers the slots information first, and then uses the slots in the second render. The problem is obvious. It doesn't support server-side rendering. There was an experimental package from the React core team called React-Core-Return, which provides a way to interpolate the children during render phase. It could be the best candidate to bring slots to React, but unfortunately, it was removed shortly. So I created the React-Slots-RFC to outline the problem with a proposal. Let me show you the code directly. Again, the typical text input component implemented in React-Slots-RFC. In the RFC, we introduced two new APIs called create-host and create-slot, which is very similar to React-Core-Return, but with a much simpler mental model. The create-host creates the template, and the create-slot creates placeholders, and then composes the slots in the host component. It's quite similar to slots for web components, but way much powerful, as we don't simply inject the elements, we interpolate them. It opens the third eye of the component. Now, the parent can see the deep details of its children, no matter how it was extended. Now, demo time, I will show you how the previous problems will be perfectly solved by React-Slots-RFC. Here, I implemented the React-Slots-RFC with React-Core-Return in 10 lines. And then, the text field, first, we create the slots for label, input, and tag. We pass the children to create-host, then it gives us the slots. Here you can see how we can interpolate the slots. That means we can do everything we want in a single place. Here you can see how I support accessibility for the text input. We can read the input ID directly for the label, and also we can iterate all the tags. Now, I will show you some magic. No matter how I compose the slots, it doesn't change the result, because the layout is defined. In the template, by create-host. In the meanwhile, we are still free to extend the slots. For example, we extend the tag, we extend the input, and we can change the order of tag, it will change the result, because it's a list. And the other problem, component-resilience. Let me try to wrap the tag with an extra node. It will work, because it's not a node. That's very important for a dedicated design system, because we have prepared the components. You should not change the layout easily. Let's change it back. And another use case is that, what if we use the slots outside of the host? Nothing will be rendered. That's also important for a consistent design system. And the listed slots are also supported. Have you noticed that how we create the text input, we don't need to create a styled text field label or text field input. Instead, we style it in the template. The slot itself renders nothing, but only a data carrier, that means a lot. For example, we can create a tree builder. Here is the example. We create a tree, but it renders nothing to the browser. You can see in the console log. Here is the tree, the listed menu, but here is how we compose them, but it's not rendered to the browser at all. But still, we can get the data, because the slot is just a data carrier. It's not needed to be rendered to the browser at all. You can see how it's reactive. So we can still benefit from all React provides to us, the life cycles, states, context, all the other things. Here is a package called React Neo, trying to do the same thing, but let's see the size. It's almost 100 KB minimized, even 30 KB minimized and gzipped. Doing the same thing, because it has to bundle the React reconciler in it. But with React Snots, we can use the React reconciler directly. Now you can see how we achieve flexibility while keeping the consistency in React Snots RFC with a decentralized customization and centralized control model. What does it mean for us? Now the host component is the single source of truth and takes control of its children, like the configuration way. So we can make composable components predictable. You can see how simple it is to add accessibility support. And because it's not necessary to render the slots into Realtometry, instead we simply connect the information and then decide what to render based on the connected information. So virtualization support is out of the box and more possibilities, for example, custom renderer. Furthermore, I created a package called create-slots, which implements the React Snots RFC fully, unlike other approaches which doesn't work well with some React features like server-side rendering. It uses pre-rendering, which is similar to React core-return to collect the children's information during render phase and use the information later during the same render phase. And then we can commit the interpolated result into the browser. And it has been used in Revolute design system already. As we are also using the composition way to build our shared components, we have almost 200 shared components and faced more problems than I have discussed here. And that eventually led me to this talk. But the package is not ideal, as it repeats React reconciler's work. That's why I still want to see the support from React itself. And that's it. If you want to discuss further, you can find me at GitHub and Twitter. Thank you.
21 min
24 Oct, 2022

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Workshops on related topic