JSX

JSX is a special notation used inside the JavaScript code to express HTML markup. It makes the code responsible for describing the view closer to the pure HTML syntax, while still having the full power of JavaScript available.

Here's an example of a render function written with JSX:

<script>
export default {
data () {
return {
movies: [
{ title: 'Star Wars' },
{ title: 'Blade Runner' },
],
}
},
render (h) {
const itemClass = 'movie'
return <ul class='movies'>
{this.movies.map(movie =>
<li class={ itemClass }>{ movie.title }</li>
)}
</ul>
},
}
</script>
You can use any JavaScript expression inside single brackets.

As you can see in this example, we can use any JavaScript code to compose our view. We can even use the map method of the movies array to return some JSX for each item. We also used a variable to dynamically set the CSS class of the movie elements.

During the compilation, what really happened is that a special module called babel-plugin-transform-vue-jsx included in babel-preset-vue transformed the JSX code into pure JavaScript code. After compilation, the preceding render function will look like this:

render (h) {
const itemClass = 'movie'
return h('ul', { class: 'movies' },
this.movies.map(movie =>
h('li', { class: itemClass }, movie.title)
)
)
},

As you can see, JSX is a syntax that helps write render functions. The final JavaScript code will be quite close to what we could have written using h (or createElement) manually.

We will cover render functions in more detail in Chapter 6, Project 4 - Geolocated Blog.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.12.36.30