Skip to main content

Unit 7: Intro to React

Welcome to Unit 7

It's time to talk about one of the most popular JavaScript libraries for building a website: React! Rather than using plain HTML, CSS, and JavaScript in our website, React lets us create more complex user interfaces more efficiently.

Unit 7 Lecture Video

What is React?

React is a JavaScript library to build user interfaces, usually websites. Created by Facebook(Meta?) in 2013, it is continually being developed in the open-source community.

React Notable Features

  • Declarative - React makes it painless to create interactive UIs. Design simple views for each state in your application, and React will efficiently update and render just the right components when your data changes. Declarative views make your code more predictable and easier to debug.
  • Component-Based - Build encapsulated components that manage their own state, then compose them to make complex UIs. Since component logic is written in JavaScript instead of templates, you can easily pass rich data through your app and keep state out of the HTML.
  • Learn Once, Write Anywhere - We don't make assumptions about the rest of your technology stack, so you can develop new features in React without rewriting existing code. React can also render on the server using Node and power mobile apps using React Native.

JSX

Alright, one more small thing before we dive in to React! React uses JavaScript, but more specifically, it's called JSX. This is a syntax extension to JavaScript.

// an example of JSX
const element = <h1>Hello, world!</h1>;

JSX combines our markup language (HTML-like), and our logic (JavaScript). This lets us combine all this into one file and make coding a little easier. How? JSX lets us embed JavaScript expressions with curly brackets {}.

const name = 'Raman Gupta';
const element = <h1>Hello, {name}</h1>;

// we can do this in element attributes as well
const imgURL = "./path/to/image.png";
const imgElement = <img src={imgURL} />;

// we use className instead of class to give elements a class
const withClass= <h2 className="example" />;

While React doesn't require using JSX, JSX is really helpful as a visual aid, and we will be using it in this lesson.

React Components

Alright, you've waited long enough. Back to React! React is built upon many components. React Components help us split the UI into smaller, isolated and reusable pieces, each with their own logic and markup.

Here's an example:

function ShoppingList(props) {
return (
<div>
<h1>Shopping List for {props.name}</h1>
<ul>
<li>"Instagram"</li>
<li>"WhatsApp"</li>
<li>"Oculus"</li>
</ul>
</div>
)
}

// Example usage: <ShoppingList name="Mark" />

ShoppingList is a React component class. A component takes in parameters called props (short for “properties”), and returns a hierarchy of views to display.

React renders elements in the React DOM (or Document Object Model). The DOM is a structured representation of the HTML elements in the web app. It is represented as a tree structure with each node being a UI element in the document. There's a lot more to understand about the DOM, but we won't go into further detail. You can learn more here:

DOM (Document Object Model) - GeeksforGeeks

React Elements

This component returns what we want our user to see on their screen. More specifically, the function returns a React element. Components are made of a hierarchy of elements.

  • Using normal JS the above example really looks like this (Beware, the code is not pretty):
    React.createElement("div", {
    className: "shopping-list"
    },
    React.createElement("h1", null, "Shopping List for ", props.name),
    React.createElement("ul", null,
    React.createElement("li", null, "Instagram"),
    React.createElement("li", null, "WhatsApp"),
    React.createElement("li", null, "Oculus")
    )
    );

It doesn't look that nice, so we will stick with using JSX.

Defining a Component

There are 2 main ways you define a component:

  • JavaScript Function
    function Welcome(props) {
    return <h1>Hello, {props.name}</h1>;
    }
  • An ES6 class
    class Welcome extends React.Component {
    render() {
    return <h1>Hello, {this.props.name}</h1>;
    }
    }

Both of these are the exact same in React. Once a component is defined, these can be used as its own element.

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}

ReactDOM.render(
<App />,
document.getElementById('root')
);

In modern React, we will use functions to define components, and other methods called Hooks , which let us use more React features. More on this later.

Props

In a lot of the previous examples, you have seen props a lot, but what are props? Props lets us pass data between components.

When we write something like this below, we are passing data to the Welcome component.

<Welcome name="Sara" />

In this instance of the Welcome component, it can access this data using the props variable. Props are treated exactly like attributes of an element in HTML. You can pass in as many as you want.

<Welcome name="Sara" title="Ms." />

// In the component the props object would look like this:
props = {
"name": "Sara",
"title": "Ms."
}

// We can use props like this
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

Props are read-only. In a component declaration, you can never modify its own props.

Hooks

Hooks are a new addition to React, and let us use React features without defining a class. Instead of defining components as a React class, we will be defining them as functions, and using Hooks to access the React state and lifecycle features of a component.

What is a Hook?

A Hook is a special function that lets you “hook into” React features. For example, useState is a Hook that lets you add React state to function components.

State Hook

When data changes, you will want to update your component, so that it shows new data. Components keep track of its data through its state variable. The state is very similar to props, but it is private to the component, and can only be controlled by the component.

We can use this simple class as an example.

import React, { useState } from 'react';

function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);

return (
<div>
<h1>Hello, world!</h1>
<h2>The counter is at {count}.</h2>
<button onClick={() => setCount(count + 1)}>
Increment!
</button>
</div>
);
}

There's a lot going on here, so let's break it up:

  1. We import the React, and useState function.
  2. useState is a Hook, that we call inside a function Component to give it a local state. A state lets us preserve these values after the function call ends.
    1. We pass in an argument to initialize the state, which is 0.
    2. useState returns a pair: the current state value count, and a function that lets you update the state to a new value setCount
      1. We use syntax called “array destructuring”. Also in Python, this lets us set variables to individual items in an array. More on this below.
  3. For the function component we return the markup for the component. Notice the use of curly brackets around our JavaScript.
    1. In <h2>, we refer to our state variable to display the current count: count
    2. In <button>, we attach the function call () => setCount(count + 1)} so when the button is clicked, the setCount is called, updating our State, and re-rendering our component.
    3. There is some wonky syntax we are using. We are defining an arrow => function that takes in no parameters, and in the function body we call setCount(count + 1)}.

Note that count is a const, so we cannot do something like count = 5

We can also declare multiple state variables

// Declare multiple state variables!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);

Destructuring

Destructuring lets us easily extract data from an array. We're setting an array to be equal to the return value of useState. This is something called Array Destructuring, a cool feature of JavaScript.

let [greeting, pronoun] = ["Hello", "I" , "love", "AntAlmanac"];

console.log(greeting); // "Hello"
console.log(pronoun); // "I"

In our example in React, useState returns an array of 2 values. The first being the value of the state variable. The second is a function to set the state variable. Array destructuring lets us immediately assign a value to these values that are returned to us. We store them in age, and setAge.

const [age, setAge] = useState(42);

We can also do Object Destructuring. This is similar to arrays, but we are instead extracting data from JavaScript objects.

let {name, organization, role} = {name: "Raman", organization: "ICSSC", role: "Projects Co-Chair"};

console.log(name); // "Raman"
console.log(organization); // "ICSSC"
console.log(role); // "Projects Co-Chair"

Note the names on the left hand side should have the same name as the property key in the object. If we want to assign a new variable name, we can. We also don't need to extract the entire object.

let {name, organization: club} = {name: "Raman", organization: "ICSSC", role: "Projects Co-Chair"};

console.log(name); // "Raman"
console.log(club); // "ICSSC"

This is also often used in function arguments.

function person({name, job}) {
console.log(name, job);
}

Back to React.

Effect Hook

The Effect Hook lets us perform side effects after our function component is rendered. useEffect tells React to call the function passed to it, after every time the component is rendered.

import React, { useState, useEffect } from 'react';

function Example() {
const [count, setCount] = useState(0);

useEffect(() => {
document.title = `You clicked ${count} times`;
});

return (
<div>
<h1>Hello, world!</h1>
<h2>The counter is at {count}.</h2>
<button onClick={() => setCount(count + 1)}>
Increment!
</button>
</div>
);
}

In this example, we pass to useEffect a function that sets the document title. We can also access the state variables in this function, because we define it inside our function component.

Rules for Hooks

  • Always use hooks at the top level. Don't call them inside nested functions, loops, or conditionals. If you want to use a conditional, place it inside the function.
  • Only call Hooks from React function components.

There are many more hooks that you can use in React. Check them out in the official documentation.

Hooks API Reference - React

More Cool Features of React

Conditional Rendering

We can choose to render a component/element based on a condition. Here, we only display the message, if unreadMessages.length > 0.

function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);
}

Rendering Multiple Components with Lists

We can render multiple elements by iterating through arrays. This is a basic List Component.

function NumberList(props) {
const numbers = props.numbers;
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
return (
<ul>
{numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
)}
</ul>
);
}

You'll notice that each list item has an attribute key. Keys are helpful for React to identify which items have changed, been added, or been removed. These should be unique identifiers for each item.

Styling with React

To add CSS styling in React, we just have to add a line at the top to import our CSS files. Remember in JSX, we use className, to give an element a class.

import "./Example.css"

function Example(props) {
return (
<h1 className="example">
Hello, world!
</h1>
)
}

Setting up React

With node installed, it also comes with npm, a package manager for node. npx is a package runner that is pre-bundled with npm. We use npx to create our first react app.

Navigate to a directory where you want to create your project. Then, run the command:

npx create-react-app my-app

my-app is the name of your app, and can be set to anything you want.

This will run some scripts, and eventually finish creating your folder my-app. Change into your project folder and run:

npm start

This will run the react app, and you will be able to see it in your browser. It will open automatically in your default browser and you will be able to see the base React project. If it doesn't open up, scroll up in your terminal, and it will tell you the URL you can find the react app at. Mine is http://localhost:3000

React Compiled Terminal Output

Deploying React to GitHub Pages

We can also share our new React website with GitHub Pages as well! This is a little less straightforward, since we are using React. We are going to have to install gh-pages , a node module that lets us publish to GitHub pages.

npm install gh-pages --save-dev

In our React project, open package.json. Add this property:

“homepage”: “https://<your-github-username>.github.io/repository-name”.

Under scripts in your package.json, add this as well

"predeploy": "npm run build",
"deploy": "gh-pages -d build"

Then, you can run, and it will deploy your app to the url above. Anytime you make changes, you just have to run this command, and it will automatically deploy the changes to your website!

npm run deploy

Assignment

This unit, we will be making a website showing off our favorite UCI classes. There will be a text input field to type in a class, and an add button, to add a new class to our list!

Required Tasks

  • Create a GitHub Repo of your project
  • Create a Home Component
    • Has a Form with a text input and submit button
    • Change state on typing input
    • Add a Class when submitting form
    • Styled with CSS
  • Create a Class Component
    • Uses props
    • Styled with CSS
  • Deploy your website to GitHub Pages

Optional Stretch Goals

  • Use Flexbox to style your website!
  • Change the Page Title

Submission

Complete the Google Form

External Resources

React has a lot of resources on its own website, that are really useful

A very cool React Tutorial