React for Beginners

ITEC 3870 Software Development II,
Alex Abraham and Cengiz Gunay

(License: CC BY-SA 4.0)

Prev - React Workshops, Next - React Authentication with Firebase Workshop

What is React Js?

A JavaScript library for building user interfaces for web as well as mobile applications developed by a team at Facebook in 2011.

  • It is an open-source, reusable component based front-end library
  • In a Model View Controller (MVC) architecture, React is the “View” which is responsible for how the app “looks and feels”. However, more accurately, it is strictly not MVC and instead uses the Flux pattern.
  • As of 2022, it is one of the most popular libraries for building Javascript libraries.

Components

Component = A piece of the UI

Independent, isolated, and reuable components, which become the building blocks to a more complex user interface.

In react, webpages are just the combination of many children components.

App: Root Component

Every React application has at least one component known as the Root Component (Most of the time named the App component).

This component represents the entire application and is where all the child components are displayed.

Here we see several components

  • NavBar
  • Feed
  • Who to Follow
  • Profile dashboard
  • Trends

Twitter Site

Take a look at all the components (which are all the rectangles with red borders).

The App (or root component) Component is the page itself that is displaying all the components.

Getting started! - Install NodeJS

NodeJS download link

It will install the tools npm, to install 3rd party plugins, and npx, for running tools.

  • npm is the node package manager, and
  • npx is the package runner that allows us to run programs without installing.

Set up your environment (IDE)

Visual Studio Code download link

Test your environment and create an app

  • Open your command prompt/terminal on Windows/Mac:

    $ node -v
    

    This is to see our version of Node.js on our device, if there’s an error, it didnt succesfully download.

  • Create your app:

    $ npx create-react-app first-react-app
    

    (first-react-app is the name of our project)

    If it works, congrats you’ve created your very first react app.

  • Start VS Code to see its contents:

    $ cd first-react-app
    $ code src/App.js
    

The root component

Run it with:

$ npm start

Open the browser

Modify the text in VScode to see changes!

React is written in JSX

JSX is an extension of Javascript that allows HTML to appear inside the code.

A React component is basically a JS function that returns HTML code:

import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
	...
    </div>
  );
}

export default App;

which is forbidden in regular Javascript.

Create your first component!

insert before App():

function MyComponent() {
  return (
    <p>
        Say my name!
    </p>
    )
}

(you can replace MyComponent with any word you like)

Then, insert before the closing </header>

<MyComponent />

(make sure it’s the same function name as above.)

Now you can save and observe the output.

Props and State

  • Props (short for properties): is an object of arbitrary inputs a React function accepts as the first argument.

  • State: is the data that changes over the lifetime of a specific instance in a react component.

Diving Into Props

  • Think of props as arguments to the component function.
  • Typically when you have a piece of code that you would like to reuse (such as 2 + 3), you can place that code into a function and any dynamic values that code used before can be accepted as arguments (such as add(2, 3)).
  • props allow passing arguments in HTML.

Diving Into Props

When we define (insert before App()):

function Add(props) {
    return (
        <div>
            {props.n1} + {props.n2} = {props.n1 + props.n2}
        </div>
        )
}

({} bring back Javascript into the HTML)

Then, insert before </header>

<Add n1={2} n2={3} />

Becomes:

2+3=5

How to use State

  • State is what controls drawing of components
  • React updates the UI only when state of a component changes
  • Think of an input text box; it only changes state when someone enters text in it

The useState function

Start by adding on the top:

import { useState } from 'react';

We will add a button to flip a coin. Let’s create state for the coin:

const [coin, setCoin] = useState(0);

Here, coin becomes the variable holding the value and setCoin is the function we will use to update the state. useState(0) sets the initial value.

Flip the coin with a button

To flip the coin, we need to call setCoin():

setCoin((coin + 1) % 2)

Put it in the onClick action of an HTML button as a callback:

<button onClick={ () => setCoin((coin + 1) % 2) } > Flip </button>

Final product with state

function Flip() {
  const [coin, setCoin] = useState(0);
  return (
      <div>
      {coin}
      <button onClick={ () => setCoin((coin + 1) % 2) }
      > Flip </button>
      </div>
  )
}

and add a line to the App() function as well, below <Add>:

<Flip />

You will get:

0

Clicking the button will flip the coin value between 0 and 1.

Routing

First install the React Router in the console/terminal:

$ npm install react-router-dom

Then, follow tutorial. Some examples:

<Switch>
    <Route exact path="/">
        <Home />
    </Route>
    <Route path="/about">
        <About />
    </Route>
    <Route path="/dashboard">
        <Dashboard />
    </Route>
</Switch>
<Router>
    <div>
        <ul>
            <li>
                <Link to="/">Home</Link>
            </li>
            <li>
                <Link to="/about">About</Link>
            </li>
            <li>
                <Link to="/dashboard">Dashboard</Link>
            </li>
        </ul>
	</div>
</Router>
Home