Vue Slots in React

Kier Borromeo
2 min readJul 24, 2018

--

In React, we pass elements to a component by simply passing elements to a prop. Here’s an example:

It works! But what if we could improve our semantics? What if we could imitate how Vue does this?

Enter Vue slots. Vue slots are a convenient way to distribute content to a component. Here’s how they work in a reusable component (let’s name it as base-layout ):

And our consuming component could use our component like so:

In React, our reusable component (named BaseLayout) can implement it by using Array.prototype.findon our this.props.children, like so.

And our consuming component can use BaseLayout in the following manner:

Seems wonderful, right? Personally, it looks easier to the eyes.

Going further

Vue slots aren’t only for content distribution. Slots can also provide state. In Vue, they call this concept scoped slots. In React, we can make use of the render prop pattern.

In this case, DataTable is a high-level component that lets you build a table, shows a loader, and fetches data from the props.endpoint. In addition, it provides you the data through the render prop provided to DataTable.Column

Disadvantages

#1: Extra weight

This may add unwanted weight to your library. It may be trivial at first, but if it’s a pattern that you use in your entire application, the trivial weight may slowly become significant overhead.

But, if you have a huge team— the extra weight might be a good tradeoff for readability.

Bonus — Make a reusable Slot HOC that does this for you.

#2: Opinionated

It also feels opinionated. This is a pattern that few libraries, if not none, implement at the moment. I only use this pattern for internal components every now and then.

Special mention

I copy-pasted the Vue slots example from the documentation itself, which is amazing, by the way!

--

--