Introduction to React

Instructor: Chris Fulton

Learning Objectives

  • What is React
    • Definition
    • Use Cases and understanding component frameworks
    • Adding React - CDN and Package manager
    • Components - Function and Class Components
  • Syntax, Structure and Rules of React
    • Understanding JSX
    • JSX Rules and Considerations
      • Attributes | Expressions | Nested Elements | CSS Style | Comments
  • React Lifecycle
    • Mounting - constructor() | getDerivedStateFromProps() | render() | componentDidMount()
    • Updating - getDerivedStateFromProps() | shouldComponentUpdate() | render() | getSnapshotBeforeUpdate() | componentDidUpdate()
    • UnMounting - componentWillUnmount()
  • React Functionality
    • React Features - Props and State | React Hooks | Routing
    • Handling Events
    • Forms

Component-based Development

Component-based software engineering (CBSE), also called components-based development (CBD), is a branch of software engineering that emphasizes the separation of concerns with respect to the wide-ranging functionality available throughout a given software system. It is a reuse-based approach to defining, implementing and composing loosely coupled independent components into systems.

Implementing React

Using Content Delivery Network

								
									
									  <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
									  <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
									  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
									
								
							

Using React Environment

								
				
									/**Create a scaffolded react application that will be contained in project
									* folder react_ex
									**/
									npx create-react-app react_ex
	
								
							

CDN React Example

Single page application with one component

						

							  
						<!DOCTYPE html>
						<html>
							<head>
							  <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
							  <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
							  <script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
							</head>
							<body>
							  
								<div id="mydiv"></div>
								
								<script type="text/babel">
									class Hello extends React.Component {
									  render() {
									    return <h1>Hello World!</h1>
									  }
									}
								
									ReactDOM.render(<Hello />, document.getElementById('mydiv'))
								</script>
							
							</body>
						</html>
							
						
					

React Environment

Single page application components

						
							 /**Create a new folder and run the command below to create a scaffolded react app**/
							 npm install -g create-react-app
							 
							 /**Run command to create a react app called example_react_app**/
							 npx create-react-app example_react_app
							 
							 /**Navigate into the example_react_app by running the command below**/
							 cd example_react_app
							 
							 /**Run the command below to start the server**/
							 npm start
							
						
					

Helpful Documentation

What is React?

Defining React

React was created by Facebook, it is an open-source JavaScript library for building user interfaces. It is used to create components, handle state and props, utilize event listeners and certain life cycle methods to update data as it changes.

component reuse

Understanding React

Components
are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and returns HTML via a render function. Components come in two types, Class components and Function components.

Props and State
Props are arguments passed into React components. Props are passed to components via HTML attributes.
State
React components have a built-in state object. The state object is where you store property values that belongs to the component. When the state object changes, the component re-renders.

Event Listeners
React can perform actions based on user events. React has the same events as HTML: click, change, mouseover etc.

Components

Class Component ⛄ Function Component

								
									import React, { Component } from "react";
									
									class Welcome extends Component {
									   state = {};
									   render() {
									      return <div> Hello {this.props.name}</div>;
									   }
									}
									
									export default Welcome;
								
							
								
									function Car() {
									  return <h2>Hi, I am also a Car!</h2>;
									}
	
								
							

JSX
(JavaScript XML)

What is JSX?

JSX is a syntax that gets compiled into valid JavaScript ★ JSX converts HTML tags into react elements ★ You do not have to use JSX, but it's easier to use JSX with React.

						
							function formatName(user) {
							  return user.firstName + ' ' + user.lastName;
							}
							
							const user = {
							  firstName: 'Silas',
							  lastName: 'Alexander'
							};
							
							const element = (
							
							  <h1>
							    Hello, {formatName(user)}!
							  </h1>
							);
							
							ReactDOM.render(element, document.getElementById('root'));

						
					

Understanding JSX

						
							var tested = true;
							var innerText = 'Offers';
							var offerReactNode = <div id=""
							                      data-test={tested?'test':'false'} 
							                      className="blue" 
							                      aria-test="test">
							                          {innerText} 
							                   </div>;
							
							ReactDOM.render(offerReactNode, document.getElementById('offers'));

						
					

Attributes
When we want to add custom attribute, we need to use data- prefix. ★ Whenever using the class attribute, we need to use className instead.

Expressions
JavaScript expressions can be used inside of JSX. We just need to wrap it with curly brackets {}.

Understanding JSX

						
							var styles = {backgroundColor:'#cd0000'};
							var innerText = 'Suggestions';
							var suggestionReactNode = ( <div id=""
							                      style={styles}>
							                      	<h1>
							                          {innerText} 
							                        </h1>
							                        {//Line Comment}
							                        {/*Block Comment...*/}
							                   </div>;)
							
							ReactDOM.render(suggestionReactNode, document.getElementById('suggest'));

						
					

Nested Elements
★ If we want to return more elements, we need to wrap it with one container element
★ To write JSX on multiple lines, wrap in parentheses

CSS Style
★ React recommends using inline styles.
★ To set inline CSS properties, we need to use camelCase syntax.

Comments
When writing comments, we need to put curly brackets {} when we want to write comment within children section of a tag.

Activity/Lab 3

MPLS Profile page components

Step 1
Create a React environment (refer to previous slides) | Navigate to this github repository and copy the img folder and profile.html code into environment file.

Step 2
Create three [offers, suggestions, task] class components

Step 3
Add JSX components to page

React Lifecycle

Lifecycle Stagest

Mounting
the process of outputting the virtual representation of a component into the final UI (e.g. DOM or Native Components). In a browser that would mean outputting a React Element into an actual DOM element.
Methods Include- constructor() | getDerivedStateFromProps() | render() | componentDidMount()

Updating
A component is updated whenever there is a change in the component's state or props.
Methods include - getDerivedStateFromProps() | shouldComponentUpdate() | render() | getSnapshotBeforeUpdate() | componentDidUpdate()

UnMounting
is when a component is removed from the DOM.
Methods include - componentWillUnmount()

React Lifecycle Stages Visual

These methods are used to control the behavior of a component

react lifecycle stages visual

Example of Mount methods

						
							const App extends React.Component {
							  constructor(props) {
							   super(props) 
							    this.state = {
							       points: 0
							    }  
							    this.handlePoints = this.handlePoints.bind(this) 
							    }   
							    
							  render() {
							    return (
							      <div className="App">
							        <header className="App-header">
							          <img src={logo} className="App-logo" alt="logo" />
							          <p>
							            You've scored {this.state.points} points.
							          </p>
							        </header>
							      </div>
							    );
							}

						
					

Constructor
The constructor can be used to bind event handlers to the component and/or initializing the local state of the component.

Render
This function takes two arguments, HTML code and an HTML element. The purpose of the function is to display the specified HTML code inside the specified HTML element

React Functionality

Props

“Props” is a special keyword in React, which stands for properties and is being used for passing data from one component to another. But the important part here is that data with props are being passed in a uni-directional flow

						
						class Car extends React.Component {
						  render() {
						    return <Garage brand ="Mazda" />;
						  }
						}
						
						class Garage extends React.Component {
						  render() {
						    return (
						      <div>
						      	<h1>Who lives in my garage?</h1>
						      	<h2> I am a {this.props.brand}! </h2>
						      </div>
						    );
						  }
						}
						ReactDOM.render(<Car />, document.getElementById('root'));

						
					

Question 1

What's used to pass data to a component from outside?

  • A. render with arguments
  • B. setState
  • C. props
  • D. state
  • E. None of the options presented

Question 2

What is state in React?

  • A. A router
  • B. A component
  • C. An internal data store (object) of a component.
  • D. a database
  • E. None of the options presented

React Routing

React Routing allows you to render the various views of the components you have within a single-page React Application. The url file path triggers which component will be displayed, and the UI remains static while components dynamically render in the browser.

						
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import { Route, Link, BrowserRouter as Router, Switch } from 'react-router-dom'
import App from './App'
import Users from './users'
import Contact from './contact'
import Notfound from './notfound'
const routing = (
   <Router>
     <div>
       <ul>
         <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/users">Users</Link>
        </li>
        <li>
          <Link to="/contact">Contact</Link>
        </li>
      </ul>
      <Switch>
        <Route exact path="/" component={App} />
        <Route path="/users" component={Users} />
        <Route path="/contact" component={Contact} />
        <Route component={Notfound} />
      </Switch>
    </div>
  </Router>
)
ReactDOM.render(routing, document.getElementById('root'))

						
					

React Hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class. Click here for documentation.

References/Resources

  • https://www.qcode.in/learn-react-by-creating-a-comment-app/
  • https://www.w3schools.com/REACT/react_props.asp
  • https://blog.logrocket.com/the-new-react-lifecycle-methods-in-plain-approachable-language-61a2105859f3/
  • React Router Walk through