Hello World Master

Tutorials, articles and quizzes on Software Development

Javascript > Articles

Learning and understanding React.js basics using Pizza

Hi, if you’re learning to learn React whether you’re new to web development, programming, or even if you’re an expert looking to try this popular framework, you’ve come to the right place.

What is “React.js”?

The first step to learning React is understanding what React is. The formal definition is that it’s a Javascript framework for building Front End Web Applications.

What, as a beginner you need to understand is React is one of many tools used to make building software easier. React is used for Front end web development, so it’s used creating the website you see in front of you.

What makes this different from using HTML, CSS, and Javascript? We are still using HTML CSS and Javascript in our website, but build(code) our applications differently. Libraries like React exist for us to make building web applications easier. There are other tools that do the same job as React such as Vue and Angular, however, in terms of popularity, React is leading in terms of job opportunities and developer mindshare.

React is seen as many things, but at the end of the day, React is used to make build scalable web applications.

How to get started

There are many ways to get started with React. We could set up an environment on our computer, however, this takes alot of time and effort.

I would visit codesandbox.io instead of setting up your project from your machine.

Setup is important, but often times the most daunting thing for beginners who want to start building things right away, if you would rather create your environment on your computer, I have an article coming up on how you can do that, but I recommend starting off using Codesandbox if you want to get started with creating things using React.

I’ll be using Codesandbox for this tutorial.


When create a new React application on Codesandbox, you will see the following code:

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

import "./styles.css";

function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

This is the default boilerplate that comes with Codesandbox. This is an example of a hello world application.

Feel free to look more into how this works, but delete this code and build our own beginner React app from scratch.

Typing out our React application

The first thing you want to do in our application is import React.js into our javascript file. This will allow you to use React to create your application. Without importing React, we won’t be able to use React.

Go into your index.jsx (Where you deleted the boilerplate code, and type the following:

import React from 'react';
import ReactDOM from 'react-dom';

Now we can use the React library in our Javascript file.

Note that we’ve also imported ReactDOM into our Javascript file. The DOM in ReactDOM stands for Document Object Model, the API ( Application programming interface ) that allows us to change things on a website.

If you’re new to programming or web development and don’t know what an API is just know that the DOM is what allows to use Javascript or a Javascript library like React to change HTML and CSS code on a web application.

ReactDOM allows us to render elements into DOM. Without it, we can still write React code, but we would not be able to see anything in the browser because we have no means of bringing our code onto the page.

We’ll look more into ReactDOM after we’ve built out our React component.

Building our React Component

Next we’re going to build our React component!

First we’re going to write a class that uses the React library we just imported. If you’re not familiar with Object oriented programming concepts from languages such as Python, Java, C++, or C#, classes are used to define a piece of information with certain characteristics.

To make the concept of a class easier, we’ll name our very first component Pizza.

import React from 'react';
import ReactDOM from 'react-dom';

class Pizza extends React.Component {
}

So what does extends React.Component do? It tells us that this is a React component that can use functions inside React.Component.

The next thing we want to do is create our Pizza. We do this using the render function that we now have access to since we extended our Pizza Component with React.Component class.

import React from 'react';
import ReactDOM from 'react-dom';

class Pizza extends React.Component {
  render() {
    <div>
       <span> I am pizza! 🍕 </span>
    </div>
  } 

Congrats, you’ve created a React component! But we’re not done yet. We still need use ReactDOM to allow our component to appear in the DOM.

To do this, we need to get the HTML element that we want to render our React application inside of. If you’re using code sandbox, head over to public/index.html and search for the following line of code:

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

This is where our React component will live inside. We will use a function in Javascript’s (not React’s) api to tell our Javascript file that we want to get this div html element with an id names root so we can use it in our Javascript file. This function is called document.getElementById

import React from 'react';
import ReactDOM from 'react-dom';

class Pizza extends React.Component {
  render() {
    <div>
       <span> I am pizza! 🍕 </span>
    </div>
  }
}

const rootElement = document.getElementById("root"); 

Finally, we’re going to use the ReactDOM function that we imported to render our Pizza component inside the root folder.

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

class Pizza extends React.Component {
  render() {
    return (
      <div>
        <span>I am pizza! 🍕</span>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Pizza />, rootElement);

Over to the browser side of CodeSandbox or Stackblitz you will see the text and emoji that’s currently inside of our span tag.

This a great Pizza we have but maybe we want more information about this Pizza. How many slices does it have? Is it sliced? Does it have any toppings?

We’re going to include what kind of toppings will go on our pizza using props!

And after that, we’re going to add how many slices are in our Pizza using a concept called state!

Concept: Adding toppings with Props

When we’re creating a pizza, decide whether or not to add toppings to our pizza. For this tutorial, I’m going to add vegetables onto our pizza.

Vegetable Pizza can have a number of different vegetables, and our pizza should represent that.

In React, props are entered into the component we created in a similar way to how we would add a class or an id to an HTML element:

<Pizza toppings = {["Peppers", "Mushrooms", "Olives"]} />

Here, the Pizza we have a Pizza component that contains. Three different Vegetable toppings. Lets pass these properties into our Pizza Component.

ReactDOM.render(<Pizza toppings = {["peppers", "olives"]} />, rootElement);

We now have a Pizza component with toppings, but we want to show that we have a toppings component on our web page.

We can do this by getting our toppings prop and since our topping is in an array, we need to use a loop to display all of our toppings!

We will create a loop using the map function, you might be thinking that we could use a for loop. While it is possible, it’s more trouble than its worth, even if you’re a for loop master.

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

class Pizza extends React.Component {
  render() {
    return (
      <div>
        <span>I am pizza! 🍕</span>
        <div>
          {this.props.toppings.map(topping => {
            return <span> I have {topping}! </span>;
          })}
        </div>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Pizza toppings={["peppers", "olives"]} />, rootElement);

Now we can see what toppings are on our Pizza using props!

Concept: State to change how many slices of pizza we have left.

In React, we change our component dynamically by using a concept called state, a set of information that defines how our component changes after it’s been rendered onto the page. State is different from props is because our component handles state, where as for props we needed to instantiate a new component inside the ReactDOM.render function. Props are passed into a new instance of our component, as we see in <Pizza toppings={[“peppers”, “olives”]} />.

State is represented as an object in React.

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

class Pizza extends React.Component {

  state = {

  }

  render() {
    return (
      <div>
        <span>I am pizza! 🍕</span>
        <div>
          {this.props.toppings.map(topping => {
            return <span> I have {topping}! </span>;
          })}
        </div>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Pizza toppings={["peppers", "olives"]} />, rootElement);

We want to use this state object to show how many slices are in the pizza. Since we start off with 8 slices, we will set our inital value that we’re going to call numberOfSlices to 8

state = {
  numberOfSlices: 8
}

Now we should see the following:

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

class Pizza extends React.Component {

  state = {
    numberOfSlices: 8
  }

  render() {
    return (
      <div>
        <span>I am pizza! 🍕</span>
        <div>
          {this.props.toppings.map(topping => {
            return <span> I have {topping}! </span>;
          })}
        </div>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Pizza toppings={["peppers", "olives"]} />, rootElement);

Great! We have 8 slices, but what if we want to change the number of slices? Normally we don’t increase the number of slices but we do decrease the number of slices by taking a slice and eating it. Let’s create a function called eatSlice below our state and over our render function

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

class Pizza extends React.Component {

  state = {
    numberOfSlices: 8
  }

  eatSlice() {
    
  }

  render() {
    return (
      <div>
        <span>I am pizza! 🍕</span>
        <div>
          {this.props.toppings.map(topping => {
            return <span> I have {topping}! </span>;
          })}
        </div>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Pizza toppings={["peppers", "olives"]} />, rootElement);

Now how are we going to decrease the number of slices? If you’re not familiar with React, but are familiar with Javascript or other programming languages, you might be thinking that we should do the following.

eatSlice() {
  this.state.numberOfSlices = this.state.numberOfSlices - 1;
}

Do not do this. Updating state directly in React is bad practice. we have a function called `setState` that we use to update our state values. Why setState? Because when we update our React component after its rendered we do more than just update that state object. The entire React component is also re-rendered. If that sounds confusing, don’t worry, just know that setState is the correct way to update our state object in React.

For setState, we pass in an object containing the values we want to either add or change. Lets pass in an object where numberOfSlices is decreased by 1

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

class Pizza extends React.Component {

  state = {
    numberOfSlices: 8
  }

  eatSlice() {
    this.setState({numberOfSlices: this.state.numberOfSlices-1});
  }

  render() {
    return (
      <div>
        <span>I am pizza! 🍕</span>
        <div>
          {this.props.toppings.map(topping => {
            return <span> I have {topping}! </span>;
          })}
        </div>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Pizza toppings={["peppers", "olives"]} />, rootElement);

Just for the sake of realism, let’s add a check if we have zero slices, then we can’t decrease the number of slices anymore, since we cant have a negative about of slices.

eatSlice() {
  if(this.state.slices > 0) {
    this.setState({numberOfSlices: this.state.numberOfSlices-1});
  }
}

We should also show the number of slice on our page, so lets show the number of slices on our page by adding a new JSX tag

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

class Pizza extends React.Component {

  state = {
    numberOfSlices: 8
  }

  eatSlice() {
    if(this.state.slices > 0) {
      this.setState({numberOfSlices: this.state.numberOfSlices-1});
    }
  }

  render() {
    return (
      <div>
        <span>I am pizza! 🍕</span>
        <div>
          {this.props.toppings.map(topping => {
            return <span> I have {topping}! </span>;
          })}
        </div>
       <span>I have {this.state.slices}!</span>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Pizza toppings={["peppers", "olives"]} />, rootElement);

We might want a way to call our eatSlice function. Lets add a button with an onClick handler that will call our eat slice function. Heres what it will look like:

<button onClick={this.eatSlice}>Eat Slice</button>

Now when we press the button, we will see that the number of slices will decrease.

Heres our final code:

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

class Pizza extends React.Component {

  state = {
    numberOfSlices: 8
  }

  eatSlice() {
    if(this.state.slices > 0) {
      this.setState({numberOfSlices: this.state.numberOfSlices-1});
    }
  }

  render() {
    return (
      <div>
        <span>I am pizza! 🍕</span>
        <div>
          {this.props.toppings.map(topping => {
            return <span> I have {topping}! </span>;
          })}
        </div>
       <span>I have {this.state.slices}!</span>
      </div>
    );
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<Pizza toppings={["peppers", "olives"]} />, rootElement);

If you made it through this tutorial, then congrats you now know how to create and manipulate your very own React component!