The HTML Code

The HTML code in this tutorial uses JSX which allows you to write HTML tags inside the JavaScript code:

Do not worry if the syntax is unfamiliar, you will learn more about JSX in the next chapter.

Example

Create a variable that contains HTML code and display it in the root node:

const myelement = (  <table>    <tr>      <th>Name</th>    </tr>    <tr>      <td>John</td>    </tr>    <tr>      <td>Elsa</td>    </tr>  </table>); ReactDOM.render(myelement, document.getElementById('root'));

 

The Root Node

The root node is the HTML element where you want to display the result.

It is like a container for content managed by React.

It does NOT have to be a <div> element and it does NOT have to have the id='root':

Example

The root node can be called whatever you like:

<body>   <header id="sandy"></header> </body>

Display the result in the <header id="sandy"> element:

ReactDOM.render(<p>Hallo</p>, document.getElementById('sandy'));

 

What is JSX?

JSX stands for JavaScript XML.

JSX allows us to write HTML in React.

JSX makes it easier to write and add HTML in React.

Coding JSX

JSX allows us to write HTML elements in JavaScript and place them in the DOM without any createElement()  and/or appendChild() methods.

JSX converts HTML tags into react elements.

You are not required to use JSX, but JSX makes it easier to write React applications.

Let us demonstrate with two examples, the first uses JSX and the second does not:

Example 1

JSX:

const myelement = <h1>I Love JSX!</h1>; ReactDOM.render(myelement, document.getElementById('root'));

 

Example 2

Without JSX:

const myelement = React.createElement('h1', {}, 'I do not use JSX!'); ReactDOM.render(myelement, document.getElementById('root'));

 

s you can see in the first example, JSX allows us to write HTML directly within the JavaScript code.

JSX is an extension of the JavaScript language based on ES6, and is translated into regular JavaScript at runtime.

Expressions in JSX

With JSX you can write expressions inside curly braces { }.

The expression can be a React variable, or property, or any other valid JavaScript expression. JSX will execute the expression and return the result:

Example

Execute the expression 5 + 5:

const myelement = <h1>React is {5 + 5} times better with JSX</h1>;

Inserting a Large Block of HTML

To write HTML on multiple lines, put the HTML inside parentheses:

Example

Create a list with three list items:

const myelement = (  <ul>    <li>Apples</li>    <li>Bananas</li>    <li>Cherries</li>  </ul>);

One Top Level Element

The HTML code must be wrapped in ONE top level element.

So if you like to write two headers, you must put them inside a parent element, like a div element

Example

Wrap two headers inside one DIV element:

const myelement = (  <div>    <h1>I am a Header.</h1>    <h1>I am a Header too.</h1>  </div>);

 

JSX will throw an error if the HTML is not correct, or if the HTML misses a parent element.

Elements Must be Closed

JSX follows XML rules, and therefore HTML elements must be properly closed.

Example

Close empty elements with />

const myelement = <input type="text" />;

 

JSX will throw an error if the HTML is not properly closed.

 

 

 

Create a Class Component

When creating a React component, the component's name must start with an upper case letter.

The component has to include the extends React.Component statement, this statement creates an inheritance to React.Component, and gives your component access to React.Component's functions.

The component also requires a render() method, this method returns HTML.

Example

Create a Class component called Car

class Car extends React.Component {  render() {    return <h2>Hi, I am a Car!</h2>;  }}

 

Now your React application has a component called Car, which returns a <h2> element.

To use this component in your application, use similar syntax as normal HTML: <Car />

Example

Display the Car component in the "root" element:

ReactDOM.render(<Car />, document.getElementById('root'));

Create a Function Component

Here is the same example as above, but created using a Function component instead.

A Function component also returns HTML, and behaves pretty much the same way as a Class component, but Class components have some additions, and will be preferred in this tutorial.

Example

Create a Function component called Car

function Car() {  return <h2>Hi, I am also a Car!</h2>;}

 

Once again your React application has a Car component.

Refer to the Car component as normal HTML (except in React, components must start with an upper case letter):

Example

Display the Car component in the "root" element:

ReactDOM.render(<Car />, document.getElementById('root'));

Component Constructor

If there is a constructor() function in your component, this function will be called when the component gets initiated.

The constructor function is where you initiate the component's properties.

In React, component properties should be kept in an object called state.

You will learn more about state later in this tutorial.

The constructor function is also where you honor the inheritance of the parent component by including the super() statement, which executes the parent component's constructor function, and your component has access to all the functions of the parent component (React.Component).

Example

Create a constructor function in the Car component, and add a color property:

class Car extends React.Component {  constructor() {    super();    this.state = {color: "red"};  }  render() {    return <h2>I am a Car!</h2>;  }}    

 

Use the color property in the render() function:

Example

class Car extends React.Component {  constructor() {    super();    this.state = {color: "red"};  }  render() {    return <h2>I am a {this.state.color} Car!</h2>;  }}

 

Components in Components

We can refer to components inside other components:

Example

Use the Car component inside the Garage component:

class Car extends React.Component {  render() {    return <h2>I am a Car!</h2>;  }} class Garage extends React.Component {  render() {    return (      <div>      <h1>Who lives in my Garage?</h1>      <Car />      </div>    );  }}

Components in Files

React is all about re-using code, and it can be smart to insert some of your components in separate files.

To do that, create a new file with a .js file extension and put the code inside it:

Note that the file must start by importing React (as before), and it has to end with the statement export default Car;.

Example

This is the new file, we named it "App.js":

import React from 'react';import ReactDOM from 'react-dom'; class Car extends React.Component {  render() {    return <h2>Hi, I am a Car!</h2>;   }} export default Car;

 

To be able to use the Car component, you have to import the file in your application.

Example

Now we import the "App.js" file in the application, and we can use the Car component as if it was created here.

import React from 'react';import ReactDOM from 'react-dom';import Car from './App.js'; ReactDOM.render(<Car />, document.getElementById('root'));

 

 

React Props

Props are arguments passed into React components.

Props are passed to components via HTML attributes.

React Props

React Props are like function arguments in JavaScript and attributes in HTML.

To send props into a component, use the same syntax as HTML attributes:

Example

Add a "brand" attribute to the Car element:

const myelement = <Car brand="Ford" />;

 

The component receives the argument as a props object:

Example

Use the brand attribute in the component:

class Car extends React.Component {  render() {    return <h2>I am a {this.props.brand}!</h1>;  }}Exampleimport React from 'react';import ReactDOM from 'react-dom'; class Car extends React.Component {  render() {    return <h2>I am a {this.props.brand}!</h2>  }} const myelement = <Car brand="Ford" />; ReactDOM.render(myelement, document.getElementById('root'));

 

Pass Data

Props are also how you pass data from one component to another, as parameters.

Example

Send the "brand" property from the Garage component to the Car component:

class Car extends React.Component {  render() {    return <h2>I am a {this.props.brand}!</h2>;  }} class Garage extends React.Component {  render() {    return (      <div>      <h1>Who lives in my garage?</h1>      <Car brand="Ford" />      </div>    );  }} ReactDOM.render(<Garage />, document.getElementById('root'));

 

 

 

If you have a variable to send, and not a string as in the example above, you just put the variable name inside curly brackets:

Example

Create a variable named "carname" and send it to the Car component:

class Car extends React.Component {  render() {    return <h2>I am a {this.props.brand}!</h2>;  }} class Garage extends React.Component {  render() {    const carname = "Ford";    return (      <div>      <h1>Who lives in my garage?</h1>      <Car brand={carname} />      </div>    );  }} ReactDOM.render(<Garage />, document.getElementById('root'));

 

React State

React components has a built-in state object.

The state object is where you store property values that belongs to the component.

When the state object changes, the component re-renders.

Creating the state Object

The state object is initialized in the constructor:

Example:

Specifiy the state object in the constructor method:

class Car extends React.Component {  constructor(props) {    super(props);    this.state = {brand: "Ford"};  }  render() {    return (      <div>        <h1>My Car</h1>      </div>    );  }}

 

The state object can contain as many properties as you like:

Example:

Specify all the properties your component need:

class Car extends React.Component {  constructor(props) {    super(props);    this.state = {      brand: "Ford",      model: "Mustang",      color: "red",      year: 1964    };  }  render() {    return (      <div>        <h1>My Car</h1>      </div>    );  }}