Seriously, check it out
Coursera: 28,848 lines of JS code..
"Model"
(Data)
Fetch data
Process data
"View"
(Presentation)
Create UI
Handle DOM Events
Using jQuery or vanilla JavaScript we would:
Lets read through this
Ready to learn more?
A module is a JavaScript library/file that you can import into your code.
This can be third party code or code files within your project
//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
return x * x;
}
export function diag(x, y) {
return sqrt(square(x) + square(y));
}
//------ main.js ------
import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5
ES6 has a new way of creating modules in JavaScript, this is something that most languages have but JS has not taken advantage of until now.
ES6 modules have the same principle (ie having code in modules and then letting certain parts be accessed)
Visual Example: Importing and Exporting
Difference between a module and a package?
A module is a single JS file that has some functionality and won’t impact other code in the rest of the application unintentionally.
A package is a directory with one or more modules inside of it and a package.json file that has information about the modules inside
This is the main source of information for your project.
Utility for downloading packages for your JavaScript projects
Can use to install front-end code, add dependencies, and build tools too!
Finding a project online or collaborating
Clone this repo, yarn install, and yarn start
Starting your own project
npm install --save [name-of-package]
A global package allows that package to be able to create commands that can be used in the command line (like yarn or npm or gulp). It can be used across your projectson your computer.
npm install -g [name-of-package]
Command for seeing the global packages on your computer: npm list -g --depth 0
There is a structure to how developers keep track of the iterations of a package or dependency
Example: 1.8.3
Build tools help you install tools, run code to help with develop, and helps get your code ready for production.
A build is just a production ready version of your app
Learning about Webpack
Helpful ImageLet's talk through this
A module bundler (at it's core)
But it also does a lot more!
You can use NPM scripts to run build commands, like starting a dev server and building production code.
More here.Setting up a JavaScript Build Environment
Everything you need to know from starting to deployment..
Click hereFacebook has made a handy tool to jumpstart your React App
npx create-react-app my-app-name
cd my-app
npm start
Let's do it
to separate my concerns (html,css,js)!!!
Now separation of concerns is divided by components not technologies :)
Components can be resuable as well as flow into each other.
Your entry file
is the JS file that is the topmost component in the tree.
import React, { Component } from 'react';
class HelloMessage extends Component {
render() {
return (
Hello World!
);
}
}
export default HelloMessage
React components implement a render() method that takes input data and returns what to display. This example uses an XML-like syntax called JSX.
The render() function creates the UI
Other parts of the component interact with the data, add the styles (CSS), etc.
Example from live website.
UserProfile
. It should include:
Avatar photo: https://randomuser.me/api/portraits/thumb/lego/8.jpg
ReactDOM.render
A library method that we will use to place components into 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!
{}
{12 + 4}
{/* comment */}
className
to assign CSS classesA property of a component that does not change. It is generally "passed down" from a parent component.
import React, { Component } from 'react';
class HelloMessage extends Component {
render() {
return (
Hello {this.props.name}!
);
}
}
export default HelloMessage
import React, { Component } from 'react';
import HelloMessage from './hellomessage'
class App extends Component {
render() {
return (
<HelloMessage name="Coach" />
);
}
}
export default App
name={someValue}
// WelcomeText accepts the prop 'name'
<WelcomeText name={'Adam'} />
// WelcomeText component
class WelcomeText extends React.Component{
render (){
return (
<p>Welcome to the class, {props.name}!</p>
);
}
};
// will output
// <p>Welcome to the class, Adam!</p>
Objects, 'this', and ES6
With an object literal:
var contact0 = {
firstName: 'Simba',
lastName: 'The Lion',
organization: 'Pride Rock'
};
Adding properties:
var contact1 = {};
contact1.firstName = 'Pumba';
contact1.lastName = 'The Warthog';
contact1['organization'] = 'The Desert';
Objects can be nested:
var contact2 = {
firstName = 'Ariel',
lastName = 'The Mermaid',
organization: {
name: 'Disney',
website: 'http://disney.com'
}
};
Two ways:
With dot notation:
contact0.firstName;
contact1.lastName;
With square bracket notation:
contact0['firstName'];
contact2['lastName'];
An object is often used as a map, or a key/value store.
These are data structures that are indexed by keys.
var appData = {
users: [{
name: 'Rihanna',
id: 2
}, {
name: 'Tina Fey',
id: 1
}
],
books: [{
title: 'Green Eggs & Ham',
author: 'Dr. Suess',
ISBN13: '978-0394800165'
}
]
};
class WelcomeIndividual extends React.Component{
render(){
return (
<li>Hi there {this.props.name}</li>
);
}
};
class WelcomeList extends React.Component {
render() {
const nameArray = ['Harrison', 'Adam', 'Laura'];
return (
<div>
{nameArray.map((item, id) =>
<WelcomeIndividual name={item} key={id} />
)}
</div>
);
}
};
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
forEach() iterates over a list and applies some operation with side effects to each list member (example: saving every list item to the database)
var words = [{name:'one'}, {name:'two'}, {name: 'three'}, {name:'four'}];
words.forEach(function(word) {
word.name = "bananas";
})
console.log(words)
Helpful MDN
this
and object methodsthis
keyword refers to the enclosing object
var currentUser = {
firstName: 'Sydney',
middleInitial: 'J',
lastName: 'Bristow',
fullName: function() {
return this.firstName + ' ' + this.lastName;
}
};
console.log(currentUser.fullName());
function getMiddleInitial() {
return this.middleInitial;
}
currentUser.mI = getMiddleInitial;
console.log(currentUser.mI()); // logs 'J'
class Welcome extends React.Component {
render(){
return (
<p>Welcome {this.props.firstName} {this.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
componentState and the Constructor
var me = {
mood: 'happy',
age: 42,
sleeping: false
};
Describe the state of water as temperature changes.
render() {
var stateOfMatter;
if (this.state.currentTemp <= 32) {
stateOfMatter = 'Solid';
} else if (this.state.currentTemp >= 212) {
stateOfMatter = 'Gas';
} else {
stateOfMatter = 'Liquid';
}
return (
At { this.state.currentTemp }°F, water is considered to be a
{ stateOfMatter } state of matter.
);
}
Local state is stored in the component itself! In something call the constructor. It is outside of the render function.
import React from 'react';
class Temperature extends React.Component{
constructor(){
super();
this.state = {
temperature: 45
}
}
render(){
//rest of render function
}
}
There is a method called setState()! woohoo!
When your user is interacting with your app, you can update the state based on their input, or based on data your app is receiving from a database.
you can include this.setState({temperature: 70}) in your program as the code of a function
class Temperature extends React.Component{
constructor(){
super();
this.state = {
temperature: 45
}
this.increaseTemp = this.increaseTemp.bind(this);
}
increaseTemp(){
this.setState(prevState => ({
temperature: prevState.temperature + 15
}));
}
render() {
var stateOfMatter;
if (this.state.temperature <= 32) {
stateOfMatter = 'Solid';
} else if (this.state.temperature >= 212) {
stateOfMatter = 'Gas';
} else {
stateOfMatter = 'Liquid';
}
return (
`At ${ this.state.temperature }°F, water is considered to be a ${ stateOfMatter } state of matter.`
);
}
}
export default Temperature
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 component:
class Welcome extends React.Component{
render() {
return (
<p>Welcome {this.props.firstName} {this.props.lastName}!</p>
);
};
class Welcome extends React.Component{
constructor(props){
super();
this.state = {
count: 10
}
}
render() {
return (
<p>
Welcome {this.props.firstName} {this.props.lastName}!
Count: {this.state.count}
</p>
);
}
})
Forms in React present some interesting challenges.
<input>
<select>
<textarea>
Try this example and see what happens!
Learn more about forms in the docs.
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 inputdefaultValue
: used if the value is null or undefinedonChange
: a general event handler, use instead of onInputhandleChange
method.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.
Component Lifecycle Methods and Styled Components
Components have a lifecycle in three phases:
Learn more about the lifecycle in the docs.
class MyComponent extends React.Component{
// required
render() { return <p>Hi!</p>; },
// Mounting: called once immediately before rendering
componentWillMount() { ... },
// Mounting: called once immediately after rendering
componentDidMount() { ... },
// Updating: called when new props are passed in
// ** may happen on 2nd and subsequent renders
componentWillReceiveProps(nextProps) {
if (this.props.thing !== nextProps.thing ) {
.. do something about it
}
}
};
class MyComponent extends React.Component{
// Updating: Invoked before rendering when new props or state are being received.
// return true to allow render, return false to prevent
shouldComponentUpdate(nextProps, nextState) {
return false;
},
// Updating: an update will occur
componentWillUpdate(nextProps, nextState) { },
// Updating: an update did occur
componentDidUpdate(prevProps, prevState) { },
// Unmounting:
componentWillUnmount() {
// do clean up to avoid memory leaks!
}
};
Just because you are running a componentWillMount() function, doesn't mean it will finish before your render() is complete.
We have already added HTML (JSX) into our JavaScript, surely we won't add CSS into our JavaScript as well....
Check out React UI Frameworks for styling (including react-bootstrap and Google Materials )
React Router and Navigation
Client-side routing in "Single-Page Applications"
More hereThank you for your attention!