React Hello World - basic structure

React is a library to build easier and better UIs. React uses javascript to build and insert HTML components into our website.

Very importantly, the HTML used in the component is actually JSX. JSX looks very much like HTML but it isn’t. There are slight differences that lets the element be used by javascript.

HTML file

<html>
    <head>
        <link rel="stylesheet" href="style.css">
        <title>Hello World from React!</title>
    </head>
    <body>
        <div id="root"></div>
        <script src="index.pack.js"></script>
    </body>
</html>

The HTML is very much the same as standard HTML. The only part we are adding in is a div with an ID of root. The id is used to let React know where to place the component that is created in React.

JavaScript file

import React from "react"
import ReactDOM from "react-dom"

These two import are required to bring in everything you’ll need to start using React. Even though React is not being called directly in our app. Without ReactDOM won’t work.

function MyInfo() {
  let message = "From inside React!";

While we could put the component directly into the render call (further down in the code). By using a function call that returns the JSX information we have a more flexable application.

We’re assigning a message to the a variable that we’ll use in the JSX. While it’s being directly assigned, we could have assigned it via an API call.

  return (
    <div>
      <h1>Hello World!</h1>
      <p>{message}</p>
    </div>
  )
}

Here we are returning the JSX that describes what we want to be inserted as the component. I’ve put the JSX in parenthesis. This is required but but it makes code a little tighter.

A very important aspect of JSX is that it can only be one element. Although it can be nested. In this case we’ve nested the h1 and the p elements inside of a div tag.

In the p element, we’re using {message} to insert the string we assigned earlier.

ReactDOM.render(<MyInfo />, document.getElementById("root"))

And finally we are using the render method to insert the JSX into the proper spot.

The first argument we are sending is the JSX element. We could have placed the JSX directly here. But instead we are putting the name of the function that needs to be called; MyInfo.

The second argument is the element we want to replace. In this case the element that has an id of root.

Resources

ReactJS.org is the homepage of react.

Scrimba’s React course is an interactive beginners course in React.