React.js

Conner Ardman | ardmanc@uw.edu

What Is React?

A JavaScript library for building user interfaces

  • A declarative, component-based JavaScript library for web applications with rapidly changing data.
  • One of the most popular libraries in industry with tons of sites built entirely or partially on it such as Facebook, Instagram, Airbnb, Dropbox, Netflix, Paypal and Reddit.

But First, A Slightly Deeper Dive Into JavaScript

Modules

Modern JavaScript optionally defines every file as a module, meaning it gets its own namespace, and we don't need the module pattern (Except not all browsers support this yet).

export function myFunc() {}

JavaScript (myjsfile.js)

import { myFunc } from "myjsfile";

JavaScript (otherfile.js)

Syntactic Sugar - Destructuring Assignment

Oftentimes we need to get a bunch of values from objects and set them to variables. We see this a lot in React.

let firstName = person.firstName;
let age = person.age;
let classes = person.classes;

JavaScript

let { firstName, age, classes } = person;

JavaScript

Destructuring Arrays

We can do the same thing to name the items of an array.

let arr = [1, 2, 3];
let [first, second, third] = arr;

console.log(first); // 1
console.log(second); // 2
console.log(third); // 3

JavaScript

Array Operations

We often have arrays that we need to perform some transformation on, and JavaScript has some great built in functions for this called map and filter amongst a few others.

Array Map

Iterates through an array performing a function on each value. Returns a NEW array without editing the original.

let nums = [1, 2, 3];
function addTwo(num) {
  return num + 2;
}

let newNums = nums.map(addTwo);
console.log(nums); // [1, 2, 3]
console.log(newNums); // [3, 4, 5]

JavaScript

let nums = [1, 2, 3];
let newNums = nums.map(num => num += 2);
console.log(nums); // [1, 2, 3]
console.log(newNums); // [3, 4, 5]

JavaScript

Array Filter

Iterates through an array performing a function on each value. If the function returns false, removes the value from the array. Returns a new array without editing the original.

let nums = [1, 2, 3, 4, 5];
let evenNums = nums.filter(num => num % 2 === 0);
console.log(nums); // [1, 2, 3, 4, 5]
console.log(evenNums); // [2, 4]

JavaScript

Okay, back to React

Disclaimer: We are about to break a lot of the rules in the Code Quality Guide. React introduces lots of new functionality into JavaScript and thus has very different style standards.

JSX - JavaScript XML

JSX is a syntax extension to JavaScript that compiles back down to native JavaScript.

Essentially it just looks like embedding HTML in JavaScript, but it is far more powerful and full featured.


						const element = 

Hello, world!

;

JavaScript

JavaScript In JSX

Since this is still JS, we can embed JavaScript code anywhere by placing it in curly braces.


						const name = "Conner";
						const src = "connerimage";

						const h1 = <h1>Hello, {name}!</h1>;
						const img = <img src={src + ".png"} alt={name} />;
					

JavaScript

Components

Components allow you to split your UI into individual, reusable pieces. Effectively this means we can create our own HTML tags!

Function Components

Standard JavaScript functions that return a single JSX element.


function Welcome() {
   return <h1>Welcome!</h1>;
}
					

JavaScript

Note: Component names must start with a capital letter. This is how React differentiates user defined components from standard HTML or XML elements.

Using Components

User defined components are used in React just like normal HTML components are! Most components will be self-closing tags.


function App() {
    return (
       <main>
         <Welcome />
         <h2>CSE 154 Is Awesome!</h2>
       </main>
    );
}
					

JavaScript

Running Example

Class Components - Mostly Outdated

JavaScript classes that extend the React.Component prebuilt class and have a render method.

  • render() will be called when the element is rendered and must return a single JSX element.

class Welcome extends React.Component {
    render() {
        return <h1>Welcome!</h1>;
    }
}
					

JavaScript

Props

props allow our components to have attributes, using standard HTML attribute syntax. These become accessable through the props parameter.

  • Props can be of any JavaScript type, including objects, arrays, functions and even other components!

Props


function Welcome(props) {
    const { name } = props; // you could also do props.name here
    return <h1>Hello, {name}</h1>;
}
				

JavaScript


<Welcome name="Conner" />
				

JavaScript


<h1>Hello, Conner</h1>
				

Compiled HTML Output

Running Example

Children Prop

children is a special name of a prop that allows our components to act like HTML containers rather than self closing tags.


function Page(props) {
    const { children } = props;
    return (
        <main>
            <Navbar />
            {children}
            <Footer />
        </main>
    );
}
				

JavaScript


<Page>
    <p>Some content</p>
</Page>
				

JavaScript

State

State allows our components to "remember" information and update whenever that information changes.

Using State

With modern react, we use the useState hook function. This function takes an initial value as a parameter then returns an array with 2 items: a variable with that state and a function to update it.


function Person() {
    const [age, setAge] = useState(0);

    const getOlder = () => {
         setAge(age + 1);
    };

    return (
        <section>
            <h1>You are {age} years old!</h1>
            <button onClick={getOlder}>Get Older</button>
        </section>
    );
}
					

JavaScript

Running Example

Putting It All Back Together

  • When we create a React app, it creates a standard HTML file for us with one div in the body and an ID "root".
  • It also creates a component called App. For all intents and purposes, App acts like our body. It is the root of our application and whatever it renders gets put in the root div on page load.
  • Usually, App will end up importing a few other user defined components that will also import other components, making a "DOM" of our components!

Running Example (Starter)

Running Example (Complete)

A Larger Example

Unfortunately, we don't have the time in this exploration session to go too deep into a larger example, but if you want to see what a larger project might look like, here is one based on our Dog fetching example.

Note: This is a doggo tier list, but to be clear all doggos do deserve S tier.

Running Example

Getting Setup Locally

There are a few reasonable ways to create a React Application, but I would recommend using Create React App.

You will first need Node and npm installed. I suspect most of you already do, but if not you can get it here. Windows users will also need a Bash terminal such as Git Bash.

Creating An Empty App

Open a terminal in the folder that you want to create your application and run this command. It will create a bunch of folders and files for you with a boilerplate React App as well as a git repository.


    npx create-react-app my-app-name
          

Bash Terminal

Running The Application

Change directories to the newly created folder (the name you typed in on create-react-app). npm start will then start the application on localhost and give you a link in the terminal to visit in your browser.

At any point you can stop the server with control-c on the terminal.


    cd my-app-name
    npm start
          

Bash Terminal

React Native

React can be used to build native mobile applications for iOS and Android! No more coding your apps twice or dealing with Swift and Kotlin!

Learn more on the official documentation.

More Resources