React

Conner Ardman | ardmanc@uw.edu

What is React?

React is a declarative, component-based JavaScript library developed at Facebook for dealing with web applications that render interfaces based on rapidly changing data.

  • It is also 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

Classes


					class Person extends React.Component {
					  constructor(name) {
					    this.name = name;
					  }

					  sayHi() {
					    alert("Hi! My name is " + this.name);
					  }
					}
				

JavaScript


					let me = new Person("Conner");
					me.sayHi(); // Alerts "Hi! My name is Conner"
				

JavaScript

Modules

Modern JavaScript 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).

  • To access classes, functions and variables in other files, we can export them from their files and import them into others!
  • There are a few ways to export such as "defaults" and "named" exports. You can read about them at MDN, but it isn't too important for our purposes.

					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 name = person.name;
					let age = person.age;
					let classes = person.classes;
				

JavaScript


					let {name, age, classes} = person;
				

JavaScript

List 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. This means we must save the return value! Remember x = change(x)?

We usually pass an arrow function in as a parameter here, but we can also use a named function:


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

						function addTwo(num) {
						  return num + 2;
						}
					

JavaScript


						let nums = [1, 2, 3];
						nums = nums.map(num => num += 2);
						console.log(nums); // [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];
						nums = nums.filter(num => num % 2 === 0);
						console.log(nums); // [2, 4]
					

JavaScript

Okay, back to React

JSX - JavaScript XML

JSX is a syntax extension to JavaScript that gets compiled back down to native JavaScript when you build the application.

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 element = 

Hello, {name}!

; 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. They take one argument called props. More on that soon.

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


function Welcome(props) {
   return 

Hello, {props.name}

; }

JavaScript

Class Components

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 based components are much more full featured and thus used more often.

						class Welcome extends React.Component {
						   render() {
						      return 

Hello, {this.props.name}

; } }

JavaScript

Using Components

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


class App extends React.Component {
   render() {
      return (
         <div>
           <Welcome name="Conner" />
           <h2>CSE 154 Is Awesome!</h2>
         </div>
      );
   }
}
					

JavaScript

Props

props allow us to pass information into our components, using HTML attribute syntax. These become accessable through the props variable (a parameter to function components or instance properties of class components)

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

class Welcome extends React.Component {
   render() {
      return 

Hello, {this.props.name}

; } }

JavaScript


<Welcome name="Conner" />
				

JavaScript

State

Class based components can also have state. This is an object similar to props, but it is controlled by the component instance itself, not values passed as attributes by the parent element.

Whenever state changes, the component rerenders itself to reflect the change.

Initializing State

Since components are classes, they still call their constructor when they are created just like any other class, so we can initialize the special "state" object there!


class Person extends React.Component {
   constructor(props) {
      super(props); // call the constructor of the "Component" class
      this.state = {
         age: 0,
      };
   }

   render() {
      return <h1>{this.props.name} is {this.state.age} years old!</h1>;
   }
}
					

JavaScript

Updating State - this.setState

NEVER directly change this.state. React has a special method to call to change state and inform the engine that the component needs to rerender.

this.setState either takes an object as a parameter and adds it to state, or it takes a callback function with an oldState parameter. This allows you to base the new state on the previous state. Never directly acces this.state in setState.


this.setState({
  age: 21,
});
  				

JavaScript


this.setState(oldState => {
  return {
    age: oldState.age + 1,
  };
});
          

JavaScript

setState Example

Notice that the returned value in setState only needs to include keys that we are changing. Other keys will be ignored.


class Person extends React.Component {
   constructor(props) {
      super(props); // call the constructor of the "Component" class
      this.state = {
         age: 0,
         hasDog: true,
      };
   }
   birthday() {
      this.setState(oldState => {
         return {
            age: oldState.age + 1,
         };
      });
   }
   render() { return <h1>{this.props.name} is {this.state.age} years old!</h1>; }
}
          

JavaScript

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!

Getting Setup

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