Learning React [Day 2] - React Basics

Posted on 30 Jun 2020 by Omar Sinan

Cover

Today I read chapters 3 and 4 of Learning React (2nd edition) by Alex Banks and Eve Porcello. Chapter 3 covered the concepts of functional programming in JavaScript using the Filter, Map and Reduce functions. Chapter 4 went over the basics of React and manipulating the DOM using React's createElement API. I'll mainly focus on React basics in this blog post.

1. The setup

Before getting started, it is important to have the proper setup in order to run React in your browser. Here is a simple boilerplate that you can use:

<html>
  <head>
    <title>React Basics</title>
  </head>
  <body>
    <script src="https://unpkg.com/react@16.12.0/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@16.12.0/umd/react-dom.development.js"></script>

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

    <script>
      // your JavaScript code goes here
    </script>
  </body>
</html>

The only two additions to a traditional empty HTML page are the two scripts provided by the unpkg CDN, namely, React and React DOM.

2. Benefits of using React

Before React, when you wanted to manipulate the DOM using JavaScript, the general approach was to interact with the DOM API directly. Now, React takes care of the hard work and rendering, as it interacts with the DOM API. All you have to do is provide React with the structure of what you want to create.

Another benefit is the ability to reuse code. Let's say you wanted to create a property listing website. One way to go about doing this is to write some HTML with a bunch of divs and then copy and paste that to create other properties:

<body>
  <div class="properties">
    <div class="property">
      <h1 class="name">Name: 4 Bedroom Apartment</h1>
      <p class="size">Size: 400 sq ft</p>
      <p class="rent">Rent: $3,200/month</p>
    <div>
    <div class="property">
      <h1 class="name">Name: 2 Bedroom Apartment Unfurnished</h1>
      <p class="size">Size: 100 sq ft</p>
      <p class="rent">Rent: $1,300/month</p>
    <div>
  </div>
<body>

You can see that this will get tiring over time. Keep reading to check how this can be improved with React :)

3. Using ReactDOM to Render React Elements

Let's create a simple React element using the createElement API representing the property's name:

const name = React.createElement("h1", null, "4 Bedroom Apartment")
ReactDOM.render(name, document.getElementById("root"))

Where the first parameter of createElement represents the type element, the second parameter represents the properties (e.g. id, class) and the third parameter represents the content that goes into the element.

Now what if we wanted to recreate the structure of a single property as in the HTML above? Well, we can use createElement and pass in multiple React elements instead of a string (i.e. "4 Bedroom Apartment"):

const property = React.createElement(
  "div",
  { className: "property" },
  React.createElement("h1", { className: "name" }, "Name: 4 Bedroom Apartment"),
  React.createElement("p", { className: "size" }, "Size: 400 sq ft"),
  React.createElement("p", { className: "rent" }, "Rent: $3,200/month")
)
ReactDOM.render(property, document.getElementById("root"))

Now that we have this structure, how can we create multiple properties without duplicating code? Well since every property has the same structure but with different data, we can create a React component that represents a property.

4. Reusing Code with React Components

Let's first start by creating an array with the two properties we have:

const properties_list = [
  {
    name: "4 Bedroom Apartment",
    size: "400 sq ft",
    rent: "$3,200/month"
  }, 
  {
    name: "2 Bedroom Apartment Unfurnished",
    size: "100 sq ft",
    rent: "$1,300/month"
  }
]

Now we can create a React component representing the properties class in the HTML code:

function PropertiesList(props) {
  return React.createElement(
    "div",
    { className: "properties" },
    props.properties.map((property, i) =>
      React.createElement(
        "div",
        { className: "property", key: i },
        React.createElement("h3", { className: "name" }, `Name: ${property.name}`),
        React.createElement("p", { className: "size" }, `Size: ${property.size}`),
        React.createElement("p", { className: "rent" }, `Rent: ${property.rent}`)
      )
    )
  )
}

So, what does this do? We start by creating a main div element with the class properties. This will hold all properties (think of it as a parent div). Then for each property in props.properties (more on that in a bit), we will create a property element just like we did above. For each of those elements we add a key property to help React when it's updating the DOM (otherwise it will complain). Then we can access the name, size and rent through property.name, property.size, property.rent, respectively.

Now let's render this:

ReactDOM.render(
  React.createElement(PropertiesList, {properties: properties_list}, null),
  document.getElementById("root")
)

This will take our properties_list array and pass it into the props object when creating the PropertiesList React component. Let's check it out:

The result of running the code. There are two properties created using the properties_list array as the data source.

Looks great! Exactly how we wanted it to look. That's pretty much it for day 2, it was a lot to digest, but it's really fun to play around with React and see the outcome right away.

Make sure you follow me on Twitter @oohsinan where I post about full-stack development (mostly React).