Please take a moment to reflect on the incredible amount of work you have accomplished over the past year!
How can we mindfully build a culture of support and community together?
Please complete all free lessons found here
We will also be building an in-class template alongside lectures.
Click here for the designs.
jQuery does not manage data.
It also requires the DOM to constantly change.
A framework, like React, handles all of these events in an organized way. You can manage your data and the UI efficiently.
React is fast. Apps made in React can handle complex updates and still feel quick and responsive.
React is modular. Instead of writing large, dense files of code, you can write many smaller, reusable files. React’s modularity can be a beautiful solution to JavaScript’s maintainability problems.
React is scalable. Large programs that display a lot of changing data are where React performs best.
React is flexible. You can use React for interesting projects that have nothing to do with making a web app. People are still figuring out React’s potential. There’s room to explore.
(they are the same as JavaScript!)
React is built on a component-driven architecture, which is critical for building large and performant web applications.
Components are reusable parts of a web application that can easily display unique data either to or from the user.
Each of the different colors represents a different component.
Check out these beautiful websites.
Identify components that you can see!
Product Menu contains Search Product, which has two child components:
to separate my concerns (HTML,CSS,JS)!!!
Now separation of concerns is divided by components and not technologies :)
With the HTML, CSS, and JavaScript for each component in one place, we are making it:
Each component --
with its HTML, CSS, and JavaScript in one place --
is reusable and easy to debug.
Each card has the same layout, stylings, and functionality.
All that changes is the data!
React is great for web applications that display dynamic data.
Dynamic data is data that changes based upon user input or is tied to a user's account.
Front end engineers often get a list of API calls from backend engineers, endpoints that exist in an application.
In React, data flows one-way, from a parent to child.
Data from an API call is best passed into the parent component to flow to its children, then to grandchildren.
Because of parent-child data flow considerations, we must think about constructing the data flow diagram carefully.
Inspect the designs to extract the data flow for Features. Assume Comments is for a particular Feature Article.
Based on the designs and discussion about data flow on the previous slide, consider creating a data flow diagram.
A data flow diagram is about tracking how the data is flowing.
Let's visit one of the following sites to hypothesize about component structure.
Then consider its possible data flow diagram.
Create a data flow diagram for the website design below.
Consider which parts of the design are likely dynamic.
We need to level up our developer toolkit
In the terminal, check your versions for:
Check out this documentation.
Sign up for a free CodeSandbox account.
Then start a project using their React template.
NPM means Node Package Manager.
So much code, so little time! You can add other tools and projects (a calendar widget or CSS framework) without having to write all the code yourself.
No longer need script tags!
Use NPM to find a project online or collaborate.
A table of contents for your code!
There is a structure to how developers keep track of the iterations of a package or dependency
Example: 1.8.3
Facebook created a handy tool to jumpstart your React App.
This video shows how to spin up a new React.js app on your local machine in seconds!
The name of this project will be handle-first-react-app
If this were my project, the commands would be:
cd documents/dev
npx create-react-app cmh-first-react-app
cd cmh-first-react-app
npm start
Now, open your finder and take a look at the folders inside of your new project!
For a quick start guide, look to Notion.
Let's take a tour in VS Code!
Your React src folder should have these folders:
Within the src folder in Pages, each folder contains at least:
Inspect the designs to identify components and the possible folder structure.
Let's build a component and discuss how to make it appear (render) and how to add content (JSX).
import React from 'react';
const HelloMessage = () => {
return (
Hello World!
);
}
export default HelloMessage;
import
: React components must import the React code to create a component with all of the React features.return
: The function will always have a return statement.export
: An export statement allows a component to be used by other components.For now, this component does not have any dynamic data.
We will use JSX to creating the UI first, and then add data.
Watch this short video.
Complete the four tasks listed in this CodeSandbox.
UserProfile
component with:
Avatar photo: https://randomuser.me/api/portraits/thumb/lego/8.jpg
ReactDOM.render
A library method that we will use to place components onto our webpage
// The ReactDOM library provides an object 'ReactDOM' with a function 'render'
// It needs the component and the target in the DOM
ReactDOM.render(<MyReactComponent />, document.getElementByID('app'));
//This is generally all the HTML you will have!
App
componentdocument.getElementByID()
What is keeping the UI from appearing?
Look at this code, solve the error and add a class!
{}
{12 + 4}
{/* comment */}
className
to assign CSS classesconsole.log()
is a great tool for debugging!
What if I want to say hello to a million different users?
What other dynamic aspects might we want in a component?
A system for passing data between components, from parent to child.
Props help display data in components in a dynamic way!
Who's my parent? Tell us!
Download the .zip for this code.
Instructions are in the README.md file.
A property of a component that does not change. It is generally "passed down" from a parent component.
import React from 'react';
const HelloMessage = (props) => {
return (
Hello {props.name}!
);
}
export default HelloMessage;
HelloMessage
is a child component receiving props from a parent.
import React from 'react';
import HelloMessage from './hellomessage';
const App = () => {
return (
<HelloMessage name="Alex" />
);
}
export default App;
App
is the parent component importing the HelloMessage
child component.
props
’ or properties for dynamic bits of data and functionality.nameOfProp={valueOfProp}
You can console.log(props)
to view its data structure!
// WelcomeText accepts the prop 'name'
<WelcomeText name={'Alex'} />
// WelcomeText component
const WelcomeText = (props) => {
return (
<p>Welcome to the class, {props.name}!</p>
);
};
// will output
// <p>Welcome to the class, Adam!</p>
See it in CodeSandbox
Props are declared on the parent component you want to pass them into, and then are passed through function arguments in the child component.
Check this CodeSandbox to get started!
Instructions are in the comments.
Front end engineers might need to build out parts of the web application before backend engineers build out their code.
So it is helpful to create and work with starter data.
You can create a JS file with data and import it into your project, and pass as props.
By using maps, we can display one component for each object that we have received from an API call.
If we have 100 user objects, we can create 100 user profile cards with a map.
An object is often used as a map, or a key/value store.
These are data structures that are indexed by keys.
const appData = {
users: [{
name: 'Rihanna',
id: 2
}, {
name: 'Tina Fey',
id: 1
}
],
books: [{
title: 'Green Eggs & Ham',
author: 'Dr. Seuss',
ISBN13: '978-0394800165'
}
]
};
Imagine the data structure for the employee page below. How many key/value pairs per employee object?
In an employeeData.js
file, create data for 3+ employees!
.map()
in React Take some time to read through the documentation
Examine the CodePens
We will discuss after!
const WelcomeIndividual = (props) => {
return (
<li>Hi there {props.name}</li>
)
};
const WelcomeList = () => {
const nameArray = ['Harrison', 'Adam', 'Laura'];
return (
<div>
{nameArray.map((item, id) =>
<WelcomeIndividual name={item} key={id} />
)}
</div>
)
};
.map()
In the previous example, the key attribute assigns a unique identifier to each of the components.
map() iterates over a list, transforms each member of that list, and returns another list of the same size with the transformed members (example: transforming list of strings to uppercase)
var array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]
Helpful MDN
const Welcome = (props) => {
return (
<p>Welcome {props.firstName} {props.lastName}!</p>
);
};
// We pass the props like this
<Welcome firstName={'Billie'} lastName={'Jensen'} />
// order doesn't matter for props
<Welcome lastName={'Lee'} firstName={'Brennen'} />
UserProfile
function so it accepts propsUserProfile
componentUse the data structure in your employeeData.js
file to make an App that maps through the data to display in the UI!
Remember to pass props from parent to child.
Storing dynamic data
var me = {
mood: 'happy',
age: 42,
sleeping: false
};
Describe the state of water as temperature changes.
const StateOfMatter = (props) => {
var stateOfMatter;
if (props.currentTemp <= 32) {
stateOfMatter = 'Solid';
} else if (props.currentTemp >= 212) {
stateOfMatter = 'Gas';
} else {
stateOfMatter = 'Liquid';
}
return (
At {props.currentTemp }°F, water is considered to be a
{ stateOfMatter } state of matter.
);
}
const [currentTemp, setCurrentTemp] = useState(props.currentTemp);
useState()
is a React Hook that allows us to declare an initial state (props.currentTemp)const [currentTemp, setCurrentTemp] = useState(props.currentTemp);
State is stored in the component itself!
It is outside of the render function.
import React, { useState } from 'react';
const Temperature = (props) => {
const [currentTemp, setCurrentTemp] = useState(props.currentTemp);
return (
The temperature is {currentTemp}
)
}
export default Temperature;
Our thermometor (our component) comes with a default temperature (this is the default value stored in state).
As the temperature changes, the thermometor updates the temperature reading (this is the setCurrentTemp function).
The value of the temperature to display to the viewer is stored as the value of currentTemp.
Setting the state means updating the value in state based on user input or the data your app is receiving from a database.
When we pass an initial value into useState()
, it returns a function we can use to update the value in state!
Let's assume we have another function of increaseTemp()
that increments temperature by 15.
import React, { useState } from 'react';
const Temperature = (props) => {
const [currentTemp,setCurrentTemp] = useState(props.currentTemp);
const increaseTemp = () => {
setCurrentTemp(currentTemp + 15);
}
}
export default Temperature;
Let's see the temperature and a button that listens for a click to execute the function of increaseTemp()
.
import React, { useState } from 'react';
const Temperature = (props) => {
const [currentTemp, setCurrentTemp] = useState(props.currentTemp);
const increaseTemp = () => {
setCurrentTemp(currentTemp + 15);
}
return (
{currentTemp}
<button onClick={increaseTemp}>Heat It Up!</button>
);
}
export default Temperature;
import React, { useState } from 'react';
const Temperature = (props) => {
const [currentTemp, setCurrentTemp] = useState(props.currentTemp);
const increaseTemp = () => {
setCurrentTemp(currentTemp + 15);
}
var stateOfMatter = (currentTemp <= 32) ? 'Solid' : (currentTemp >= 212) ? 'Gas' : 'Liquid';
return (
<div>
<p>At { currentTemp }°F, water is considered to be a
{ stateOfMatter } state of matter.</p>
<button onClick={increaseTemp}>Heat It Up!</button>
</div>
);
}
export default Temperature;
import React from 'react';
import Temperature from './Temperature';
const Parent = () => {
return (
<Temperature currentTemp={47}/>
);
}
export default Parent;
yay react!
Make sure you got the original code to work.
How would you add a button to decrease the temperature?
How would you reset the temperature to 45?
A presentational child component:
import React from 'react';
const Welcome = (props) => {
return (
<p>Welcome {props.firstName} {props.lastName}!</p>
);
}
export default Welcome;
import React, { useState } from 'react';
const Welcome = (props) => {
const [firstName, setFirstName] = useState(props.firstName);
const [lastName, setLastName] = useState(props.lastName);
const [count, setCount] = useState(props.count);
//more code here informing how state changes upon user or data input
return (
<p>
Welcome {firstName} {lastName}!
Count: {count}
</p>
);
}
export default Welcome;
Remember that console.log()
is your friend!
When you are working with forms in React, you can store the user's inputs into state.
<input>
<select>
<textarea>
Input controls in React provide a few props that are designed to keep the UI state information synchronized with the underlying DOM:
value
: the current value of the inputonChange
: a general event handler, use instead of onInput
Try this example and see what happens!
Remember: React has one-way data flow!
You can't send data (as state or props) up to the parent.
Only props can be sent down from a parent to a child.
Components Lifecycle references:
Components have a lifecycle in three phases:
useEffect()
gets called every time a component renders or rerenders with an update to state.
We can limit its execution to only certain changes:
import React, { useState, useEffect } from 'react';
const Lyrics = (props) => {
const [lyrics, setLyrics] = useState("");
useEffect(() => {
let response = await fetch(`https://api.lyrics.ovh/v1/${props.artist}/${props.title}`);
setLyrics(response);
}, []);
return (
<div>
Lyrics: {lyrics}
</div>
);
}
export default Lyrics;
useEffect()
can accept two arguments:
useEffect(() => {
let response = await fetch(`https://api.lyrics.ovh/v1/${props.artist}/${props.title}`);
setLyrics(response);
}, []); //Only calls useEffect once
useEffect(() => {
setTitle("Song Title: " + props.title)
}, [props.title]); // calls useEffect any time props.title changes
Just because you are running a useEffect() function
DOES NOT mean it will finish executing
BEFORE your component's initial render is complete.
Create a form that accepts the user's city. Implement the useEffect() hook to call this Weather API to display current weather data for that city.
Remember to check the API documentation!
We have already added HTML (JSX) into our JavaScript, surely we won't add CSS into our JavaScript as well....
Similar to website development projects, CSS can also be applied to React applications in three ways:
In general, external CSS files are siblings of their respective JS files in the directory.
Example: App.css
is a sibling of App.js
So to import an external CSS file into a JS file:
//In the App.js file:
import "./App.css";
External CSS is great for the overall styling of parent pages housing reusable components.
Internal CSS groups behavior (JS) with markup (JSX) and styling (CSS), which is quite helpful for child components. React component libraries help to apply such styles.
Example: Material UI library has a makeStyles
method.
import { makeStyles } from "@material-ui/core/styles";
const useStyles = makeStyles((theme) => ({
root: {
display: "flex"
}
}));
Importing the method and applying the styles is the first step. Next, we must apply the styling to the JSX.
After importing and declaring the styles to be used in a component, the next step is to apply the styling to the markup via the export
and return
.
export default function [name of function](parameter(s)) {
const classes = useStyles();
}
return (
<div className={classes.root}>
<h1>JSX (markup)</h1>
</div>
)
Internal CSS is great for component-scoped styling in child components. So when a component breaks, we can easily find and debug its accompanying markup, styling, and behavior.
Inline CSS applies styling to a specified JSX element.
//for a to do list:
function getList({item, isDone}) {
return (
<div>
<p style={{ color: isDone ? "green" : "red" }}>{item}</p>
</div>
)
}
Inline CSS can be used for a nonreusable component or element.
Although other tools exist to apply styling in React applications, the general rule is:
Check out React UI Frameworks for styling, including:
React Router and Navigation
Client-side routing in "Single-Page Applications"
More hereDiscuss which concepts relate to Data Flow and which concepts impact the User Interface here.
Thank you for your attention!