Check out bidbear.io Amazon Advertising for Humans. Now publicly available 🚀

React: Getting Started With React and JSX

Intro

In our last project we did all of our coding online with an Amazon EC2 server and Cloud 9 IDE. This time we are going to develop with a local installation of node and use Visual Studio.

References

Official JSX Docs

Setup

First we want to globally install a package called create-react-app with

npm install -g create-react-app

Then we navigate to the location we want the app to live and we create a new application with this

create-react-app (name of app)

Then you have to cd into the app folder and you can start it with npm start

default react home screen

Now delete all the src files we are going to make our own.

Importing React & ReactDOM

// import react and reactDOM libraries
import React from 'react';
import ReactDOM from 'react-dom';

Here we are importing the modules and giving them variable names, just like we have done in our previous Express applications.

Creating Components

A component is a class or a function that produces HTML to show the user using JSX, and then receives feedback from the user.

// create a React component
const App = () => {
    return <div> Hello World </div>;
}

So we can see here that we have created a function that returns a simple div. Next step is to display it on the screen.

// take react component and show it on the screen
ReactDOM.render(
    <App />, 
    document.querySelector("#root")
);

and we can see that we have queried an object in the document with class #root which is referencing the following div in our public/index.html file

<div id="root"></div>

and if we save that and start the server with npm start we can see “Hello World” in the browser. First React component is complete!

What is JSX?

JSX is syntax inside of React that looks like standard HTML, but it actually gets converted via Babel and React to standard Javascript when you compile the application. JSX simply makes it easier to write and understand the content inside of our react modules, as the raw Javascript gets messy very quickly.

// create a React component
const App = () => {
    return <div> Hello World </div>;
}

The div inside of this example looks like HTML, but it is in fact JSX. So to recap, JSX is:

  • Special dialect of JS (it’s not html)
  • Browsers don’t understand JSX. We write JSX and then run tools to convert it into JS
  • Very similar in form and function to HTML with a couple differences

Conventional JSX Syntax

In the interest of keeping everything legible, the conventional syntax for JSX is to return the start of the JSX to the line after return, however this will cause an error if we don’t place anything on the same line as return, so you then place parentheses around all of the content and indent the JSX one tab. If you are using a formatter like Prettier this will all be done for you.

// create a React component
const App = () => {
  return (
    <div>
      <table>
        <thead>
          <tr>
            <th colspan="2">The table header</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>The table body</td>
            <td>with two columns</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
};

Differences Between JSX and HTML

Inline Styling

HTML inline styling would use the following syntax.

<div style="background-color: gray;">

In JSX we must convert the style definition to a Javascript object like so.

<div style={{backgroundColor: 'gray'}}>

Note the camelCase in backgroundColor.

If we want to put in multiple different styles, instead of separating with a ; we will use a , like you typically would to separate items inside of a Javascript Object.

<table style={{backgroundColor: 'gray', border: '1px solid black'}}>

Assigning Classes

In JSX when assigning classes we must use className instead of class.

<div className="first-div">

Reference Javascript Variables

With JSX we can easily insert Javascript variables into our templates. For example we can create the variable tableHeader and then reference it in our table with {tableHeader}.

const App = () => {
  const tableHeader = 'Nick Coughlin';
    
  return (
    <div className="first-div">
      <table style={{backgroundColor: 'gray', border: '1px solid black'}}>
        <thead>
          <tr>
            <th colspan="2">{tableHeader}</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>The table body</td>
            <td>with two columns</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
};

table with Nick Coughlin in header

We can also reference functions just as easily.

function getTableHeader() {
    return 'Nick Coughlin';
  }

  return (
    <div className="first-div">
      <table style={{backgroundColor: 'gray', border: '1px solid black'}}>
        <thead>
          <tr>
            <th colspan="2">{getTableHeader()}</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>The table body</td>
            <td>with two columns</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
};

Values JSX Can’t Show

Javascript Objects

One thing that we cannot do is display a Javascript Object, we can only display the value of an object. For example if we change the value of our variable to be an object like so:

const tableHeader = {text: 'Nick Coughlin'};

We will get an error.

error, objects are not valid react children

However if we changed our reference to include the key of the string that we were looking to display that would be a valid reference

<th colspan="2">{tableHeader.text}</th>

This further explains our syntax for the table styles above. If we wanted to we could easily create an object for our style and then reference that object.

const App = () => {
  const tableHeader = {text: 'Nick Coughlin'};
  const tableStyle = {backgroundColor: 'gray', border: '1px solid black'};

  return (
    <div className="first-div">
      <table style={tableStyle}>
        <thead>
          <tr>
            <th colspan="2">{tableHeader.text}</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>The table body</td>
            <td>with two columns</td>
          </tr>
        </tbody>
      </table>
    </div>
  );
};

Forbidden Property Names

This is something that is not application breaking but will still throw a warning in the console if you do this. There are certain HTML properties like for when assigning a label to an input that React developers feared would become mixed up with the for loop. So input labels must be tethered to their inputs with HTMLfor.

Official JSX Docs

Amazon Ad Analytics For Humans

Advertising reports automatically saved and displayed beautifully for powerful insights.

bidbear.io
portfolios page sunburst chart