Using JSX with Vue.js

Tram Ho

1. JSX?

JSX is a popular extension for JavaScript that enables XML tokens in your scripts.

For example:

This tag syntax is not a string or HTML, it is called JSX. Facebook uses JSX to render UI components

JSX = Javascript + XML

If you want to create patterns in your script files and you find Vue’s render() function hard to work, then JSX might be what you need.

For example, here is a render() function without JSX:

and with JSX:

Much easier, right

Of course, browsers cannot understand JSX. It must first be translated into standard JavaScript, similar to the way SASS first needs to be translated into CSS

2. Why use JSX with Vue?

There are many ways to specify a template in Vue:

a. Use the HTML file

b. Use an attribute template in your instance / component builder

c. Use the <template> tag in single file components

d. Use render.

If you go with the last option, you must create your buttons in a very strange way, ie using JavaScript syntax createElement .

JSX allows you to use the render function and still have the HTML interface. Some people find this a lot easier. Others find it awful to use HTML with their JS.

Take a look at this example and you can decide if you like it or not:

JSX example

Now we will create a simple application, displaying a message with text content. When you click on the card it will give a notification.

First, use Vue the usual way with separate JS and HTML files:

vue.js

index.html

Combine with render:

vue.js

index.js

Combining JSX

The rendering function is a little hard to read, right? And that’s just an ordinary <span> tag, imagine using it for a more complex component!

Use JSX only:

vue.js

index.html

3. Transpiling JSX

JSX is only for development and will be transpiled long before running. So we just need to consider JSX on how it benefits us (or not).

To transpiled your JSX, you can use the babel-plugin-transform-vue-jsx module which is the plugin for Babel and Webpack. Just add it to your Webpack configuration:

Now, when you do build the webpack package, your JSX will be transpiled into standard code.

References:

  1. https://en.vuejs.org/v2/guide/render-function.html
  2. https://medium.com/js-dojo/using-jsx-with-vue-js-846f4fbbf07f
  3. https://github.com/vuejs/babel-plugin-transform-vue-jsx
Share the news now

Source : Viblo