Modern component reusability: Render props in React & scoped slots in Vue
Tags: webdev, react, frontenddev, vue
Published: 2018-08-10 20:04:15

---
title: Modern component reusability: Render props in React & scoped slots in Vue
published: true
tags: web-development,react,front-end-developmen,vue
canonical_url: https://blog.logrocket.com/modern-component-reusability-render-props-in-react-scoped-slots-in-vue-ff3c5b2dc899
---

![](https://cdn-images-1.medium.com/max/1024/1*wOPY1wHGN0wc6EESA9Nw7g.jpeg)

One of the issues all front-end developers face is how to make UI components reusable. How do we craft components in such a way that satisfies the narrow use case that is clear to us now, while also making them reusable enough to work in a variety of circumstances?

Let’s say we are building an autocomplete component:

![](https://cdn-images-1.medium.com/max/1024/1*v3_4oPZRiulzwLVmCcD2Xg.png)

Take a look at the initial React component code:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/680362e8187c03d2477406e8eac49aa1/href">https://medium.com/media/680362e8187c03d2477406e8eac49aa1/href</a></iframe>

In this component, we have some logic that controls the core search behavior, but we also specify how the input and search results will be rendered. In this instance, we render a div that serves as a dropdown container and an unordered list containing a list item for each result within it.

Think about how you would reuse this component. Sure, you could use this very same component if you want to reproduce exactly the same behavioral and visual result. But what if you want to reuse the same behavior, but visualize the component slightly differently? What if you want to reuse the core search behavior but add a few modifications for a slightly different use case?

Imagine that instead of a dropdown containing the search results, you want a tag-like list of search results that always display:

![](https://cdn-images-1.medium.com/max/1024/1*XaTfw2O0izYAKGancHTItg.png)

At their core, the functionality of these two components is very similar: type into an input to filter a list.

This is a perfect use case for some relatively new tools that modern JavaScript frameworks now provide. These are _render props_ in React and _scoped slots_ in Vue. They work very similarly and provide a way to separate the **behavior** of a component from its **presentation**.

[![](https://cdn-images-1.medium.com/max/1024/1*GPjaPKNNUYHU8EsA3Z0JGA.png)](https://logrocket.com/signup/)

### Render props in React

First, let’s look at how we would restructure our autocomplete component using render props in React. We will now have two components — one for our Autocomplete component and one for a core SearchSelect component.

Let’s look at the SearchSelect component first:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c4d06376a44b1c0b86514f3c45f0528/href">https://medium.com/media/1c4d06376a44b1c0b86514f3c45f0528/href</a></iframe>

This is a _renderless_ component (one that doesn’t render any markup of its own). Rather, it returns the result of a special prop called a _render prop_. This render prop accepts an object, into which you can pass any data that you would like the parent component to have access to.

Think of this as the opposite of normal props. Usually, props are passed down from parent to child. In the case of render props, these are returned from the child so the parent can access them.

Our SearchSelect component is handling the lowest level functionality — filtering a list of options based on a query string. It is then using the special render prop to render an element.

In the parent, we pass a function to the render prop of the SearchSelect component. This function returns a React element, which we can hydrate with state and behavior from the SearchSelect component itself. Basically, this means we are able to access data from the child component in the parent.

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30330a7c6ff4bd97ec85bbf37d83b5eb/href">https://medium.com/media/30330a7c6ff4bd97ec85bbf37d83b5eb/href</a></iframe>

The key to making this work is the arguments we pass to the render prop function. See how we are destructuring a single object and using those destructured properties inside our markup? This object should be passed as an argument when you call this.props.render() in the child component.

All this means that we can write whatever markup we want, as long as we properly hydrate it with the data and behavior exposed by the SearchSelect component.

Also, note how we are passing the method for filtering our list in as a prop. This will allow us to change the way our list of options is filtered, while still using the SearchSelect component.

Let’s look at how we would implement our tag-like list component. We use the same SearchSelect core component and just change the markup rendered by the render prop:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d904b3f1befe858a83d50c77f74c22d2/href">https://medium.com/media/d904b3f1befe858a83d50c77f74c22d2/href</a></iframe>

Check out the working example:

<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fjonathanharrell%2Fembed%2Fpreview%2FKeOmVV%3Fheight%3D600%26slug-hash%3DKeOmVV%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fjonathanharrell%2Fpen%2FKeOmVV&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1527504.KeOmVV.small.ed5b977a-8b31-4760-ba93-6bac56ec9dcc.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2aef8f38deddc2fb66113218eb3aed7/href">https://medium.com/media/a2aef8f38deddc2fb66113218eb3aed7/href</a></iframe>
### Scoped slots in Vue

Now let’s look at how we would implement this in Vue using scoped slots. First, here’s our SearchSelect component (for this example I am using globally registered components but you should probably use single file components in a real project):

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bec185b8e045eeee1a93d3b5de71c5d0/href">https://medium.com/media/bec185b8e045eeee1a93d3b5de71c5d0/href</a></iframe>

As you can see, this looks very similar to the render prop in our React component. Here, we are returning a default _scoped slot_, which passes along an object with whatever we want. Here, we give it the results and our search method.

In our Autocomplete component, we use the slot-scope attribute to get access to the data from the child component. We can destructure the properties that come through for easier access, in much the same way as in our React render prop argument:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ea8235036674cd748a6b0a42b94170c/href">https://medium.com/media/3ea8235036674cd748a6b0a42b94170c/href</a></iframe>

Check out the working example:

<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fjonathanharrell%2Fembed%2Fpreview%2FVdobNO%3Fheight%3D600%26slug-hash%3DVdobNO%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fjonathanharrell%2Fpen%2FVdobNO&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F1527504.VdobNO.small.11a2fba2-882f-4db6-9bb8-93db56153d53.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/0857cf6f6e04ecd7474aa4ae3bca497c/href">https://medium.com/media/0857cf6f6e04ecd7474aa4ae3bca497c/href</a></iframe>
### Other uses for render props & scoped slots

Creating reusable interface components isn’t the only use for render props and scoped slots. Here are some other ideas for how you can use them to encapsulate reusable behavior in a component that can then be exposed to its parent.

**Data provider components**

You can use render props/scoped slots to create a component that handles asynchronously fetching data and exposing that data to its parent. This allows you to hide the logic for hitting an endpoint, getting the result and handling possible errors, as well as displaying a loading state to users while the data fetch is in progress.

Here’s what the base component could look like:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07e6800392836f1eb45a9334b8281252/href">https://medium.com/media/07e6800392836f1eb45a9334b8281252/href</a></iframe>

It accepts a URL as a prop and handles the actual fetching logic. Then, we use it in a parent component:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6085caf2eb8fb05eb62e9cd522cf94e9/href">https://medium.com/media/6085caf2eb8fb05eb62e9cd522cf94e9/href</a></iframe>

**Observers (resize, intersection, etc.)**

You can also use render props/scoped slots to create a component that acts as a wrapper around resize or intersection observers. This component can simply expose the current size or intersection point of an element to a parent component. You can then perform whatever logic you need based on that data in the parent, preserving a nice separation of concerns.

Here is a base component that observes its own size and exposes its height and width to its parent:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0ce776a7ba80d718ad4035651cd6ec8/href">https://medium.com/media/d0ce776a7ba80d718ad4035651cd6ec8/href</a></iframe>

We are using the [Element Resize Detector](https://github.com/wnr/element-resize-detector) library to listen to changes in our element size, and a React ref to get a reference to the actual DOM node.

We can then use this component quite easily in our app:

<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4b31bd49f3cdaac44e1f4ae5fba0977/href">https://medium.com/media/a4b31bd49f3cdaac44e1f4ae5fba0977/href</a></iframe>
### Conclusion

The key to successfully creating reusable components using both render props and scoped slots is being able to correctly separate **behavior** from **presentation**. Each time you create a new UI component, think “What is the core behavior of this component? Can I use this anywhere else?”

Having a core set of renderless components that use render props or scoped slots can help you cut down on code duplication in your app and think more carefully about your core interface behaviors.

### Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps

[![](https://cdn-images-1.medium.com/max/1024/1*s_rMyo6NbrAsP-XtvBaXFg.png)](https://logrocket.com/signup/)<figcaption><a href="https://logrocket.com/signup/">https://logrocket.com/signup/</a></figcaption>

[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single page apps.

[Try it for free.](https://logrocket.com/signup/)

* * *