First React Component with JSX

In this exercise you are going to create your FIRST React component!

Getting Started with JSX

JSX is an extension of JavaScript. In traditional web development you deal with separate HTML and JS files. HTML is converted into the DOM (Document Object Model) and DOM-JavaScript manipulates and responds to the user with the HTML to create interactive websites.

You can essentially write HTML by using JavaScript DOM methods such as document.createElement("div"). It's much easier to write HTML than creating it through JavaScript methods, but it can be a little cumbersome working with multiple connected HTML and JS files. ENTER JSX!

JSX combines your HTML and JavaScript into one easy to use file by injecting HTML into your JavaScript. React has strongly embraced JSX. It isn't natively supported by web browsers, and for this reason it has to be transpiled (converted) into JavaScript.

Here is a simple Hello World example

// a simple Hello component 

var Hello = React.createClass({
     render: function(){
          return <h1 id="hello" > Hello World! </h1>
      }
})

Most of this looks just like JavaScript, except for the the <h1> Hello World! </h1> thrown in there. When this code is transpiled, the browser sees it like this:

"use strict";

var Hello = React.createClass({
     displayName: "Hello",

     render: function render() {
          return React.createElement(
               "h1",
               { id: "hello" },
               " Hello World! "
          );
     }
});

Simply put, JSX allows us to write our HTML AND JavaScript in ONE FILE. 🤗

React Components

The Hello example above is an example of a simple React component. Components are sometimes called classes because when when you create a component you actually create a JavaScript class that contains the HTML and JavaScript for the browser.

React components can be written into HTML as an HTML element. For example the Hello component can be inserted like this:

<body>
    <Hello/> <!--this is self closing because nothing is nested inside of it-->
</body>
Two ways to create classes

React is flexible and just uses JavaScript. There are multiple ways to write React components. However, here are the two most popular:

with es5

 var NavBar = React.createClass({
     render: function(){
          return (<nav>
                    <a href="/home" />
                    <a href="/about" />
                    <a href="/contact" />
                  </nav>)
      }
})

The es5 way of creating components uses the createClass method. This methods takes an object as an argument and returns a React component (class).

with es6

class NavBar extends React.Component{
    render(){
        return (<nav>
                    <a href="/home" />
                    <a href="/about" />
                    <a href="/contact" />
                  </nav>) 
     }
}

The es6 way of creating components uses the JavaScript class syntax. The class syntax is new to JavaScript and it is simple and powerful. It brings behaviors and functionality that closely resembles the class functionality of other programming languages such Java, C#, etc... ES6 provides many advantages, like less lines of code, simplicity, and increased SPEED. It's also more commonly used in React, so you are more likely to find examples, questions, and answers that use es6. This document will provide both es5 and es6 examples of how to do things, but the tutorials following this one will use es6 exclusively. Don't worry though, we will talk more about how to use es6 classes.

The render method

Every React class must have a render method. The render method is what actually delivers the HTML that will be displayed on the user's screen. The render method is a function that will simply return JSX.

RULE: If a render method returns more than a single line of HTML, the HTML must be wrapped in (parentheses).

// One line of HTML, so no parentheses necessary
return <h1>hello world!</h1>
// Returns multiple lines of HTML, so parentheses are necessary. 
return   return (<nav>
                    <a href="/home" />
                    <a href="/about" />
                    <a href="/contact" />
                  </nav>) 

Anther RULE: The render method must return a single parent HTML element. The element can have multiple nested children, as long as nothing is outside of the parent element.

// returns a single element with nested elements inside
// this will work
return (<form>
           <input type="text" placeholder="Firstname"/>
           <button onClick="submitForm()">Submit</button>
        </form>)

// returns a multiple elements that are not wrapped in a parent element
// this will throw an error
return (<input type="text" placeholder="Firstname"/>
        <button onClick="submitForm()">Submit</>)

Putting it together

To get started clone or download the files in this git repository.

You will need to navigate to the folder in your terminal and run npm install to get all of the necessary node modules.
...This may take few minutes.

Before we get into the nitty gritty, er, beauty of writing JSX, let's take a look at the files we have to work with.

You should have this basic file structure:

root
|
__app
|     |_index.html
|     |_index.js
|     |_style.css
|     |_style.js
|
|_package.json
|_webpack.congfig.js
|_.babelrc
|_.nvmrc

Let's examine these files.

  • You may notice that we have both a styles.css AND a styles.js file. This may seem odd, but there is good reason for it. With React components, the style attribute accepts a JavaScript object with camelCased properties. We will be using both CSS and JS style objects.

  • The package.json files contain the node modules necessary to get your first React component functioning.

  • The webpack.config.js file contains some configuration that we will use to transpile our JSX code to good ol' JavaScript. We don't have to use a transpiler or JSX to write React, but it is highly recommended, so we are going to start using it from the start. We will discuss webpack more later.

Let's examine our two main files: index.html and index.js.

index.html
<!doctype html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>

    <div id="app"></div>

    <script src="./dist/index.bundle.js"></script>
</body>

</html>

You can see that our HTML is linked to a JS file named index.bundle.js inside a folder named dist. Those don't exist yet but they will be created when Webpack transpiles our React code. We won't start with the file, but we'll add it as extra credit.

Finally, the <div id="app"></div> line of code which React will use to populate the entire app.

index.js
import React from "react";
import ReactDOM from "react-dom";

Our JS only has two imports right now. This is the es6 way of writing:

//es6
var React = require("react");
var ReactDOM = require("react-dom");

Below these imports, write out the following React component. You can choose to use the es5 or es6 version right now.

// es5
// use this or es6 but NOT both

var Hello = React.createClass({
    render: function() {
      return (
        <div>
          <h1>Hello World!</h1>
          <h2>This is my first React component!</h2>
       </div>
      )
    }
})

// es6
class Hello extends React.Component {
    render() {
        return (
            <div>
                <h1>Hello World!</h1>
                <h2>This is my first React component!</h2>
            </div>
        )
    }
}

Lastly, we need to tell React where to put this HTMl. To do this we will use ReactDOM. Facebook (the creators of React) separated ReactDOM away from the core React library so the React core could be used with other rendering engines like React Native and in server-side rendering.

Below our React Hello component, use the ReactDOM.render method to display our new element. The ReactDOM.render method takes to parameters: a component, and the target where the component will display.

// es5 & es6
ReactDOM.render(<Hello/>, document.getElementById("app"));

Now, simply run npm start in your terminal. This will transpile your code and serve up your app. Now go to http://localhost:8080/ in your web browser.

If you see your HTML, Congratulations! you just wrote your first React web component!

** Extra credit **

Remember how our index.html was linked to a file called index.bundle.js? It didn't exist, right? Our React worked without it, but we can create it really easily, and we should have it.

  • Install Webpack globally by running npm install -g webpack.
  • Stop your server and run the command webpack in your console. This will create transpile your JSX and put it in a new folder called dist.
  • Run your server again with npm start