Intro To React
ππππΎππ»π
A hands on and practical introduction to React development.
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. With React, we are able to compose complex UIs from small and isolated blocks of code called "Components". A component is the equivalent of a jquery-ui style HTML "widget" that encompasses both functionality and aesthetic styling. Furthermore, a component is typically defined by a data scheme - usually stored as a "state" variable or passed along as a "prop" from another component. React is "declarative" in that we tell it what to do and worry less about "how" to do it.
Getting Started
Before we begin, let us explore some class tools and resources that we will be leveraging as we traverse this course. There are a few ways to install and run React - in the next few sections we will be exploring them along with details as to how to get set up with each approach.
Basic HTML
The simplest approach is to create an index.html
page that contains a react development build.
You can copy and paste the following into a simple HTML page:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello World</title>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
</script>
</body>
</html>
Just copy-pasta this code into your favorite code editor, save as index.html
and then open up the browser and point it to your file! React will run locally!
Important Notes
- This is NOT suitable for use in production
- The react resource being imported is a large development build of React
- Babel transform is occuring in the browser, which is very slow
Online Environments
There are a lot of tools available that allow us to write react code inside the browser. Using these tools, we can write react code that more closely resembles production code.
Codesandbox
Codesandbox is nice in that it allows us to create a "virtual" filesystem and write code as if React's build dependencies are already pre-installed.
This tool is free and ready to use from the get-go and therefore is highly recommended for usage in building small react apps to understand the underlying principles governing this framework.
Local Environment
Because React performs many code transformations, it is imperative that our local environments have NodeJS and a few other packages preinstalled (babel, webpack, etc).
Assuming these packages are pre-installed, we can create our own custom task runners that will analyze our React code, transform it and "build" it. However, it easy enough to utilize Create React App to do the grunt work of pre-installing all the task runners for us.
Using create-react-app
, we are able to do everything codesandbox allows us to do, but in our local machines.
Topics
Let's learn React by doing. In particular, we will build a few simple apps to explore how React and React components work.
Basic Terminology
Here are some of the basic vocabulary words we will leverage to get started:
Data
An entity that represents what we want to display on the screen. DATA is the heart of any react application as it is the source of truth that drives all other interactions and views.
Component
A bit of code - either a class or a function - that knows how to interpret a piece of data and render interactable elements on screen. A component encompasses the logic that defines HOW to display and mutate the data of your application
Props
A prop, short for "property", defines how we can pass data along into our components. This is the primary / preferred way to tell the component what the data is that we are attempting to display.
State
A state is similar to a prop, except that it is component specific. This means that each component has the ability to maintain internal state.
EXAMPLE: If we have a react component that represents a user profile, the prop would be the API call that returns user data from the server. However, as the user is updating fields - we represent these changes in the state (as they can be abandoned at any time) - and once user performs an action such as SUBMIT, etc we post this data back to the DB so that the prop when user revisits profile is up to date.
Lifecycle
All react components encompass a concept of the component "lifecycle". Every time a prop or state is updated, the component lifecycle is triggered.
Shopping List
Let's implement a shopping list as follows:
- It includes two fields - one for name of item and one for price
- On adding new item, it updates the total and the total with tax
- We are able to also remove and/or edit items as we see fit.
Tic Tac Toe
Let's implement a tic-tac-toe game as follows:
- Supports two players who alternate turns
- Can detect if someone has won and stop game
- We can "track" every move made and "time travel" through the game once completed
Notes
Please find class notes here.
Notes for April 6 2019
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
const ShoppingListItem = props => {
const label = props.label;
const price = props.price.toFixed(2);
const quantity = props.quantity;
const labelStyles = {
fontWeight: "bolder"
};
return (
<div className="line-item">
<span
style={{
paddingRight: "5px"
}}
>
{quantity}
</span>
<span style={labelStyles}>{label}</span>=
<span>${(quantity * price).toFixed(2)}</span>
</div>
);
};
const ShoppingList = props => {
const shoppinglist = props.shoppinglist;
console.log(shoppinglist)
let total = 0;
const ShoppingListItems = [];
for (let item of shoppinglist) {
console.log(item);
total += item.price * item.quantity;
ShoppingListItems.push(
<ShoppingListItem
key={item.label}
label={item.label}
price={item.price}
quantity={item.quantity}
/>
);
}
return (
<div>
{ShoppingListItems}
TOTAL: ${total}
</div>
);
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
label: "",
price: 0,
quantity: 0,
currentTotal: null,
shoppingList: [],
};
}
addToList() {
const shoppingList = this.state.shoppingList;
shoppingList.push({
"label": this.state.label,
"price": parseFloat(this.state.price, 10),
"quantity": parseInt(this.state.quantity, 10),
})
// make DB call to POST / PUT here
this.setState({
label: "",
price: 0,
quantity: 0,
currentTotal: null,
shoppingList: shoppingList,
})
}
updateState(e, name) {
const oldState = this.state;
oldState[name] = e.target.value;
if (oldState.price && oldState.quantity) {
oldState.currentTotal = oldState.price * oldState.quantity
}
else {
oldState.currentTotal = null;
}
this.setState(oldState)
}
render() {
const inputStyle = {
padding: '10px',
fontSize: '14px',
margin: '5px',
display: 'block',
width: '100%'
}
const buttonStyle = {
width: '100%',
border: 'none',
fontSize: '14px',
fontWeight: 'bolder',
backgroundColor: 'black',
color: 'white',
margin: '5px',
padding: '10px',
}
const currentTotal = this.state.currentTotal ? ("$" + this.state.currentTotal): null
console.log(this.state.shoppingList)
return (
<div className="App">
<input style={inputStyle} onChange={(e) => this.updateState(e, "label")} type="text" placeholder="Shopping Item Label" />
<input style={inputStyle} onChange={(e) => this.updateState(e, "price")} type="number" step="0.01" placeholder="Shopping Item Price" />
<input style={inputStyle} onChange={(e) => this.updateState(e, "quantity")} type="number" placeholder="Shopping Item Quantity" />
<span>{currentTotal}</span>
<button onClick={() => this.addToList()} style={buttonStyle}>Add!</button>
<ShoppingList shoppinglist={this.state.shoppingList} />
</div>
);
}
}
// const shoppinglistArr = [
// {
// label: "Eggs",
// price: 1.99,
// quantity: 1
// },
// {
// label: "Coffee",
// price: 8.99,
// quantity: 5,
// },
// {
// label: "chicken",
// price: 5.99,
// quantity: 10,
// }
// ];
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
About
Built by your boy Taq Karim with this, this, βββ and β€οΈ.
Find the project source on github.