Bootcamp
Search…
📅
Course Schedule
0: Language and Tooling Teaching Guide
1: Frontend Basics Teaching Guide
2: Backend Basics Teaching Guide
3: Backend Applications Teaching Guide
4: Backend Structure Teaching Guide
5: Full-Stack Applications Teaching Guide
6: Frontend Infrastructure Teaching Guide
7: React Teaching Guide
8: Advanced React Teaching Guide
9: Advanced Topics Teaching Guide
🧮
Algorithms Teaching Guide
💼
Interview Prep Teaching Guide
☺
User Experience Teaching Guide
7.1: JSX Intro

Introduction

JSX is a JS "syntax extension" that allows us to specify HTML elements directly in JS. We use JSX with React to specify elements we want React to manipulate. In this module we'll create a sample app with JSX.

Setup

Clone Repo

Install Packages

Install React libraries and Babel preset for React.
1
npm install --save-dev react react-dom @babel/preset-react
Copied!

Update Webpack Config to Support React

  1. 1.
    Update the test regular expression (line 3) to include our new file extension, .jsx.
  2. 2.
    Add the React preset to the presets key (line 8).
1
{
2
// regex to see which files to run babel on
3
test: /\.(js|mjs|jsx)$/,
4
exclude: /node_modules/,
5
use: {
6
loader: require.resolve('babel-loader'),
7
options: {
8
presets: ['@babel/preset-env', '@babel/preset-react'],
9
},
10
},
11
},
Copied!

Sample webpack.dev.js

The full Webpack dev config should look like the following.
1
const HtmlWebpackPlugin = require('html-webpack-plugin');
2
const path = require('path');
3
const { merge } = require('webpack-merge');
4
const common = require('./webpack.common.js');
5
​
6
module.exports = merge(common, {
7
entry: {
8
main: './src/index.js',
9
},
10
mode: 'development',
11
devtool: 'inline-source-map',
12
watch: true,
13
plugins: [
14
new HtmlWebpackPlugin({
15
// name this file main, so that it does not get automatically requested as a static file
16
filename: './main.html',
17
template: path.resolve(__dirname, '..', 'src', 'main.html'),
18
}),
19
].filter(Boolean),
20
module: {
21
rules: [
22
{
23
// regex to see which files to run babel on
24
test: /\.(js|mjs|jsx)$/,
25
exclude: /node_modules/,
26
use: {
27
loader: require.resolve('babel-loader'),
28
options: {
29
presets: ['@babel/preset-env', '@babel/preset-react'],
30
},
31
},
32
},
33
],
34
},
35
});
Copied!

JSX Syntax

The following are examples of how we might create a div with inner text in DOM, React, and JSX syntax respectively. Eventually we will write React with JSX syntax, combining the best of React with JSX. Try to execute the JSX code in Chrome DevTools- we should get a syntax error.
We set up Babel in our Webpack config to automatically transform JSX to React. Note that @babel/preset-env needs to be specified before @babel/preset-react so that ES6 gets transformed to ES5 before JSX gets transformed to React.
1
presets: ['@babel/preset-env', '@babel/preset-react'],
Copied!

DOM JavaScript

1
const myEl = document.createElement('div');
2
myEl.innerText = 'Hey Wow!';
Copied!

React JavaScript

1
const myEl = React.createElement('div', null, 'Hey Wow!');
Copied!

JSX

1
const myEl = <div>Hey Wow!</div>;
Copied!

Minimal JSX App

Render a div element with React and JSX. 1 common property of React apps is that the DOM is only ever mentioned once, at app setup with react-dom's render function. This is true of apps like ours below and apps with millions of lines of code. render tells React which element to render all other DOM elements into.

src/index.js

1
import React from 'react';
2
import { render } from 'react-dom';
3
import './styles.scss';
4
​
5
// Create JSX element and log it.
6
const myEl = <div>Hey Wow!</div>;
7
console.log('myEl: ', myEl);
8
​
9
// Create root element to render other elements into, add root element to DOM.
10
const rootElement = document.createElement('div');
11
document.body.appendChild(rootElement);
12
​
13
// Render the myEl JSX element into the root element with React.
14
render(myEl, rootElement);
Copied!
Run the watch command to have Webpack auto-compile our code.
1
npm run watch
Copied!
Run our Express server in a new terminal to serve our website.
1
npx nodemon index.mjs
Copied!
Visit http://localhost:3004/home in Chrome to view our element.

Using CSS Classes with React

In JSX and React, HTML elements can't have a class attribute because the HTML class keyword conflicts with JavaScript's class keyword. JSX has chosen to replace class with className. React will translate className to class such that our browsers know what CSS to apply.
1
const myEl = <div className="hero-text">Hey Wow!</div>;
Copied!

JSX with Multiple HTML Elements

So far we've used JSX to create a single HTML element and rendered that element onto our page. Our equivalent DOM code would be the same length or shorter. The real benefit of JSX is the ability to specify a set of nested elements in the same way we would write HTML. How many lines would the equivalent DOM code be?
There are a few rules when writing longer JSX.
  1. 1.
    Surround multi-line JSX expressions with parentheses.
  2. 2.
    1 JS variable contains at most 1 JSX element. Note the myEl variable contains a single element even though it has other elements inside it.
1
import React from 'react';
2
import { render } from 'react-dom';
3
​
4
// Create JSX element and log it.
5
const myEl = (
6
<div>
7
<h1 className="hero-text">
8
Hey <span className="warning">Wow!</span>
9
</h1>
10
<p>Lorem Ipsum!!</p>
11
</div>
12
);
13
console.log('myEl: ', myEl);
14
​
15
// Create root element to render other elements into, add root element to DOM.
16
const rootElement = document.createElement('div');
17
document.body.appendChild(rootElement);
18
​
19
// Render the myEl JSX element into the root element with React.
20
render(myEl, rootElement);
Copied!

JSX Templating with Data

Basic Templating Example

We can inject JS variables into JSX, similar to how we injected JS variables into EJS. In EJS we used <%= %> syntax, but in JSX it's {}. In the following example, we initialise a number on line 4 and use it on line 12.
1
import React from 'react';
2
import { render } from 'react-dom';
3
​
4
const myRandomNum = Math.random();
5
​
6
// Create JSX element and log it.
7
const myEl = (
8
<div>
9
<h1 className="hero-text">
10
Hey <span className="warning">Wow!</span>
11
</h1>
12
<p>Random Value: {myRandomNum}</p>
13
</div>
14
);
15
console.log('myEl: ', myEl);
16
​
17
// Create root element to render other elements into, add root element to DOM.
18
const rootElement = document.createElement('div');
19
document.body.appendChild(rootElement);
20
​
21
// Render the myEl JSX element into the root element with React.
22
render(myEl, rootElement);
Copied!

Templates Accept Any JS Code

Curly braces in JSX can contain any valid JavaScript code.
1
const myEl = (
2
<div>
3
<h1 className="hero-text">
4
Hey <span className="warning">Wow!</span>
5
</h1>
6
<p>Random Value: {Math.random() * 100}</p>
7
</div>
8
);
Copied!

Template Substitution Also Works in Element Attributes

JSX also allows templating of HTML attribute values, not just HTML element contents. We need not specify quotations around HTML attribute values. In the following example we initialise a URL string on line 1 and use it in an href attribute on line 7.
1
const myUrl = 'http://google.com';
2
const myEl = (
3
<div>
4
<h1 className="hero-text">
5
Hey <span className="warning">Wow!</span>
6
</h1>
7
<a href={myUrl}>Random Value: {Math.random() * 100}</a>
8
</div>
9
);
Copied!

Further Reading

Read more about JSX on the official docs: https://reactjs.org/docs/introducing-jsx.html​

Exercise

Replicate the above code.
Last modified 2mo ago