What are Renderless Components?

Asked

Viewed 92 times

4

What exactly is the utility of a Renderless component? Is there any real advantage to its use?

  • 1

    Worth seeing: https://adamwathan.me/renderless-components-in-vuejs/

1 answer

4


A component Renderless is a component that does not generate HTML itself, it exists only to structure other components and/or process data that is passed to the inside of it. A component Renderless is a specific case of High order.

Imagine a scenario where you want to show even numbers or odd numbers. The functionality of filtering even or odd numbers can be extracted and set aside. Thus passing a different template to the component renderless takes care of processing data stays outside HTML.

Example with a component <lista>:

Vue.component('lista', {
  props: ['numbers', 'even'],
  computed: {
    filteredNumbers() {
      return (this.numbers || [])
        .filter(nr => this.even === (nr % 2 === 0));
    }
  },
  render() {
    return this.$scopedSlots.default({
      numbers: this.filteredNumbers
    });
  }
});

new Vue({
  name: 'App',
  el: "#app",
  data() {
    return {
      numbers: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    }
  }
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>

<div id="app">
  <p>Pares</p>
  <lista :numbers="numbers" :even="true">
    <ul slot-scope="{numbers}">
      <li v-for="nr in numbers">{{nr}}</li>
    </ul>
  </lista>
  <p>Ímpares</p>
  <lista :numbers="numbers" :even="false">
    <div slot-scope="{numbers}">
      <span>{{numbers.join(', ')}}</span>
    </div>
  </lista>
</div>

Two articles in English with more detailed examples:

  • React Or Vuejs? :)

  • 1

    @Marconi is indifferent, the concept is the same but in each technology is made slightly different. I gave an example with Vue but could be with React.

  • Sergio I did was a joke of which of the two prefer... :)

  • 1

    @Marconi prefer Vue :) Both libraries are good.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.