JSX Components

Updated: 03 September 2023

Based on this EdX course

Setting Up ReactJs

To add react to an HTML file we include the following scripts in the head

1
<!DOCTYPE html>
2
<html>
3
<head>
4
<meta charset="UTF-8" />
5
<script src="https://unpkg.com/react@15/dist/react.min.js"></script>
6
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
7
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
8
</head>
9
<body></body>
10
</html>

And in the body we can add a script to render an element as follows

1
<body>
2
<div id="root"></div>
3
<script type="text/babel">
4
ReactDOM.render(<div>Hello World</div>, document.getElementById('root'))
5
</script>
6
</body>

We can also create a ReactJs CodePen by including the above scripts and using the Babel Javascript Preprocessor

What is ReactJs

React is a library that generates the view layer of an application based on its state. These applications are made from React Components which describe the properties and state of UI components

React makes use of a Virtual DOM and when component states are updated the React Library calculates the most efficient way to update the actual DOM

This turns out to be much faster than re-rendering the entire DOM

React Elements

React Elements are Objects that represent a DOM node and are written in JSX. React elements are different to React components

React elements need to be rendered by the ReactDOM.render() method, this can be done as follows

1
<div id="root"></div>
1
var element = <h1>Hello World!</h1>
2
ReactDOM.render(element, document.getElementById('root'))

Once the DOM is rendered, it will remain the same until the render method is called again

1
var num = 0
2
function updateNum() {
3
ReactDOM.render(<div>{num++}</div>, document.getElementById('root'))
4
}
5
6
setInterval(updateNum, 100)

JSX

JSX is a syntax extension on Javascript that allows React Elements to be written in JS with HTML tags

We can see the difference between using JSX and just JS below

1
var element = <h1>Hello World!</h1>
1
var element = React.createElement('h1', null, 'Hello World!')

Embed JS

Furthermore we can embed javascript expressions inside of elements using curly brackets

1
var str = 'World!'
2
var element = <h1>Hello {str}</h1>
1
var item = {
2
name: 'Cheese',
3
price: 5,
4
}
5
6
var element = (
7
<p>
8
{item.name} : R{item.price}
9
</p>
10
)
1
var length = 20
2
var width = 10
3
4
function calculateArea(x, y) {
5
return x * y
6
}
7
8
var element = <div>The Area is: {calculateArea(length, width)}</div>

Element Attributes

We can also use JSX for element attributes

1
var element = <button className="deleteButton"> Delete </button>
2
var element = <img src={product.imageURL}></img>

Note that the " " in JSX indicates a string literal. Do not use this to pass in JS attributes

Empty Tags

JSX can simply be used with self closing tags as well

1
var element = <input className="nameInput" />

Style Objects

As well as to define styles for an element

1
var styleObject = {
2
backgroundColor: 'red',
3
color: 'blue',
4
fontSize: 25,
5
width: 100,
6
}
7
8
var element = <input style={styleObject} />

We can even define an element styles using the curly braces for the style object

1
var element = <input style={{ width: 200, height: 100 }} />

Nested Elements

Elements can be nested within other elements, however these need to be wrapped in a single parent element

1
var element = (
2
<div>
3
<div>Hello World</div>
4
<div>Hello World</div>
5
</div>
6
)

It is also recommended to surround these with parenthesis in order to avoid semicolon insertion

Also note that certain attributes are named differently in React, for example class is called className

React Components

React components are reusable components

React has two types of components, namely Functional and Class

Functional Components

Functional components are just functions that output React Elements, by convention the first letter is capitalized and can be created by referencing the component name

1
function HelloWorld() {
2
return <h1>Hello World!</h1>
3
}
4
5
var element = <HelloWorld />
6
7
ReactDOM.render(<HelloWorld />, document.getElementById('root'))

Component Properties

Functional components can also have properties such as

1
function HelloWorld(props) {
2
return <h1>Message: {props.message}</h1>
3
}
4
5
ReactDOM.render(
6
<HelloWorld message="Hello World!" />,
7
document.getElementById('root')
8
)

Properties can be any type of javascript object, such as:

1
function HelloWorld(props) {
2
return <h1>Value: {props.numberArray[props.index]} </h1>
3
}
4
5
ReactDOM.render(
6
<HelloWorld index="3" numberArray={[1, 2, 3, 4, 5]} />,
7
document.getElementById('root')
8
)

Anything passed through props will be accessible

Component Composition

Functional components can include other components inside of them, such as in the following example which will output a list of shopping items

1
function ShoppingTitle(props) {
2
return (
3
<div>
4
<h1>{props.title}</h1>
5
<h2>Total Number of Items: {props.numItems}</h2>
6
</div>
7
)
8
}
9
function ListItem(props) {
10
return <li>{props.item}</li>
11
}
12
13
function ShoppingList(props) {
14
return (
15
<div>
16
<h3>{props.header}</h3>
17
<ol>
18
<ListItem item={props.items[0]} />
19
<ListItem item={props.items[1]} />
20
<ListItem item={props.items[2]} />
21
</ol>
22
</div>
23
)
24
}
25
26
function ShoppingApp(props) {
27
return (
28
<div>
29
<ShoppingTitle title="My Shopping List" numItems="9" />
30
<ShoppingList header="Food" items={['Apple', 'Bread', 'Cheese']} />
31
<ShoppingList header="Clothes" items={['Shirt', 'Pants', 'Hat']} />
32
<ShoppingList header="Supplies" items={['Pen', 'Paper', 'Glue']} />
33
</div>
34
)
35
}
36
37
ReactDOM.render(<ShoppingApp />, document.getElementById('root'))

Conditional Rendering

We can render components based on conditional information by simply using if-else statements or a conditional operator inline

1
function Feature(props) {
2
if (props.active) {
3
return <h1>Active</h1>
4
} else {
5
return <h1>Inactive</h1>
6
}
7
}
1
function Feature(props) {
2
return <h1>{props.active ? 'Active' : 'Inactive'}</h1>
3
}

We can also completely prevent rendering by returning null or with the && operator

1
function Feature(props) {
2
if (props.active) {
3
return <h1>{props.message}</h1>
4
} else {
5
return null
6
}
7
}
1
function Feature(props) {
2
return props.active && <h1>{props.message}</h1>
3
}