Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Fragments in Vuejs 2.x if using Jsx?

Given that, React has Fragments and the official github thread too doesn't offers any solution as such.

What would be the workaround for that in Vuejs. This might help developers migrating to Vuejs from React background i.e who prefer render function styles and JSX?

like image 730
HalfWebDev Avatar asked Nov 07 '22 01:11

HalfWebDev


1 Answers

This is simple, if you're not doing it for the root element of the component. For example you already have a root div having multiple nodes returned from sub-render functions.

As we used to divide the render functions in React, we can do the same way here.

Solution:

Here is the code

render(h) {
    return (
      <div>
        {this.isConfirm ? this.renderF1(h) : this.renderF2(h)}
      </div>
    );
},
methods: {
    //eslint-disable-next-line
    renderF1: function(h){
        return [
            <div></div>,
            <div class='anotherDiv'></div>
        ]
    },
    //eslint-disable-next-line
    renderF2: function(h){
        return [
            <span></span>,
            <div class='secondDiv'></div>
        ]
    }
}

Explanation:

First step is to return the multiple root node elements from array like this

return [node, node];

Next, Vue CLI will throw an error for function h. So from your main render function simply pass h as an argument to those other smaller render functions.

After this code should run.

Note - if you have eslint, you just might want to add this line

//eslint-disable-next-line

on top of each render function to avoid compilation error.

Further - If you're coming first time to JSX land in Vuejs, I used official Babel plugin package

So if you can try to work around with your component hierarchies in a way, you atleast have something to work on. Using array as return as a root element results in error though

For example, if we did

render(h) {

 return [
      <div>
        {this.isConfirm ? this.renderF1(h) : this.renderF2(h)}
      </div>
    ];
},

Vue errs out this

Multiple root nodes returned from render function. Render function should return a single root node.

like image 58
HalfWebDev Avatar answered Nov 14 '22 18:11

HalfWebDev