27
ReactJS What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework (unlike Angular). React is an open-source project created by Facebook. React is used to build user interfaces (UI) on the front end. React is the view layer of an MVC application (Model View Controller) Setup and Installation There are a few ways to set up React. 1. Static HTML File This first method is not a popular way to set up React , but it will be familiar and easy to understand .It's the least scary way to get started if you're not familiar with Webpack, Babel, and Node.js. Let's start by making a basic index.html file. We're going to load in three CDNs in the head - React, React DOM, and Babel. We're also going to make a div with an id called root, and finally we'll create a script tag where your custom code will live. 'We new to load the latest stable versions of the libraries as of the time of this writing.

Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

  • Upload
    others

  • View
    14

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

ReactJS

What is React?

React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub.

React is not a framework (unlike Angular). React is an open-source project created by Facebook. React is used to build user interfaces (UI) on the front end. React is the view layer of an MVC application (Model View Controller)

Setup and Installation

There are a few ways to set up React.

1. Static HTML File

This first method is not a popular way to set up React , but it will be familiar and easy to understand .It's the least scary way to get started if you're not familiar with Webpack, Babel, and Node.js.

Let's start by making a basic index.html file. We're going to load in three CDNs in the head - React, React DOM, and Babel. We're also going to make a div with an id called root, and finally we'll create a script tag where your custom code will live.

'We new to load the latest stable versions of the libraries as of the time of this writing.

React - the React top level API React DOM - adds DOM-specific methods Babel - a JavaScript compiler that lets us use ES6+ in old browsers

The entry point for our app will be the root div element, which is named by convention. And the text/babel script type, which is mandatory for using Babel.

index.html<!DOCTYPE html><html> <head>

Page 2: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

<meta charset="utf-8" />

<title>Hello React!</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/[email protected]/babel.js"></script> </head>

<body> <div id="root"></div> </body></html>

<script type="text/babel"> // React code will go here </script>

</body></html>

Now, let's write our first code block of React. We're going to use ES6 classes to create a React component called App.

class App extends React.Component { //...}

Now we'll add the render() method, the only required method in a class component, which is used to render DOM nodes.

class App extends React.Component { render() { return ( //... );

Page 3: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

}}Inside the return, we're going to put what looks like a simple HTML element. Note that we're not returning a string here, so don't use quotes around the element. This is called JSX

class App extends React.Component { render() { return <h1>Hello React!</h1> }}

Finally, we're going to use the React DOM render() method to render the App class we created into the root div in our HTML.

ReactDOM.render(<App />, document.getElementById('root'))

-

Here is the full code for our index.html.

index.html

<!DOCTYPE html><html>

<head> <meta charset="utf-8" />

<title>Hello React!</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/[email protected]/babel.js"></script> </head>

<body> <div id="root"></div> </body></html>

Page 4: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

<script type="text/babel"> class App extends React.Component { render() { return <h1>Hello world!</h1> } }

ReactDOM.render(<App />, document.getElementById('root')) </script>

</body></html>

Now if we view index.html in the browser, we'll see the h1 tag we created rendered to the DOM.

Page 5: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

2. Create React App

The method used of loading JavaScript libraries into a static HTML page and rendering the React and Babel on the fly is not very efficient, and is hard to maintain.

Fortunately, Facebook has created Create React App, an environment that comes pre-configured with everything you need to build a React app. It will create a live development server, use Webpack to automatically compile React, JSX, and ES6, auto-prefix CSS files, and use ESLint to test and warn about mistakes in the code.

To set up create-react-app, run the following code in your terminal.

Note: Make sure you have 5.2 or higher in Node.js.

>npx create-react-app react-tutorial

Once that finishes installing, move to the newly created directory and start the project.

>cd react-tutorial>npm start

Once you run this command, a new window will popup at localhost:3000 with your new React app.

Page 6: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

It creates the project structure, which consists of /public and /src directory, along with the regular node_modules, .gitignore, README.md, and package.json.

The /public, consists index.html, which is very similar to the static index.html file we made earlier - just a root div. This time, no libraries or scripts are being loaded in. The /src directory will contain all our React code.

Go ahead and delete all the files out of the /src directory by keeping just index.css and index.js.

Now in index.js, we're importing React, ReactDOM, and the CSS file.and Create our App component .

import React, { Component } from 'react'import ReactDOM from 'react-dom'import './index.css'

class App extends Component { render() { return ( <div className="App">

Page 7: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

<h1>Hello, React!</h1> </div> ) }}

ReactDOM.render(<App />, document.getElementById('root'))

Page 8: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

JSX:

JSX is an XML/HTML-like syntax used by React that extends ECMAScript so that XML/HTML-like text can co-exist with JavaScript/React code. The syntax is intended to be used by preprocessors (i.e., transpilers like Babel) to transform HTML-like text found in JavaScript files into standard JavaScript objects that a JavaScript engine will parse.

JSX is actually closer to JavaScript, not HTML, so there are a few key differences to note when writing it.

className is used instead of class for adding CSS classes, as class is a reserved keyword in JavaScript.

Properties and methods in JSX are camelCase - onclick will become onClick.

Self-closing tags must end in a slash - e.g. <img />

JavaScript expressions can also be embedded inside JSX using curly braces, including variables, functions, and properties.

const name = 'CVR'const heading = <h1>Hello, {name}</h1>

Virtual DOM

Today, we mostly don't think of a website as a collection of web pages anymore. Instead, we build web applications that might have only one web page, and that web page does not represent the layout for our content—it represents a container for our web application. Such a web application with a single web page is called (unsurprisingly) a Single Page Application (SPA).

Once you load your web page in a web browser, it creates a Document Object Model (DOM) of that web page. A DOM represents your web page in a tree structure, and at this point, it reflects the structure of the layout that you created with only HTML tags. This is what happens regardless of whether you're building a traditional web page or a SPA

If you are building a traditional web page, then you would finish creating your web page's layout. On the other hand, if you are building a SPA, then you would need to start creating additional elements by manipulating the DOM with JavaScript.

Page 9: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

However, manipulating (or mutating) the DOM with JavaScript has two issues:

Your programming style will be imperative if you decide to use the JavaScript DOM API directly. This programming style leads to a code base that is harder to maintain.

DOM mutations are slow because they cannot be optimized for speed, unlike other JavaScript code.

React solves both these problems for us.

Because our web applications are not static. They have a state represented by the user interface (UI) that a web browser renders, and that state can be changed when an event occurs. There are two types of events that we're interested in:

User events: When a user types, clicks, scrolls, resizes, and so on Server events: When an application receives data or an error from a server, among others

when a state of our data model changes, we might want to reflect this change by updating a state of our UI. Looks like what we want is a way of syncing two different states: the UI state and the data model state. We want one to react to the changes in the other and vice versa. One of the ways to sync your application's UI state with an underlying data model's state is two-way data binding.

Instead of two-way data binding, React offers a different solution called the virtual DOM. The virtual DOM is a fast, in-memory representation of the real DOM, and it's an abstraction that allows us to treat JavaScript and DOM as if they were reactive. Let's take a look at how it works:

1. Whenever the state of your data model changes, the virtual DOM and React will rerender your UI to a virtual DOM representation.

2. React then calculates the difference between the two virtual DOM representations: the previous virtual DOM representation that was computed before the data was changed and the current virtual DOM representation that was computed after the data was changed. This difference between the two virtual DOM representations is what actually needs to be changed in the real DOM.

3. React updates only what needs to be updated in the real DOM.

The process of finding a difference between the two representations of the virtual DOM and rerendering only the updated patches in a real DOM is fast.

Page 10: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

React Elements:An element is a plain object describing a component instance or DOM node and its desired properties. It contains only information about the component type (for example, a Button), its properties (for example, its color), and any child elements inside it.React elements are not what we see in the browser. They are just objects in memory and we can’t change anything about them.It’s just an immutable description object with two fields: type: (string | ReactClass) and props: Object.

React Component:A React Component is a template. A blueprint. A global definition. This can be either a function or a class (with a render function).

Components are the building blocks of any React app and a typical React app will have many of these. Simply put, a component is a JavaScript class or function that optionally accepts inputs i.e. properties(props) and returns a React element that describes how a section of the UI (User Interface) should appear.

Components let you split the UI into independent, reusable piec--es, and think about each piece in isolation. Conceptually, components are like JavaScript functions. They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen.

There are two main types of components in React. Class Components and Functional Components. Class components are ES6 classes and Functional Components are functions. The only constraint for a functional component is to accept props as an argument and return valid JSX.

Functional Component

These components are purely presentational and are simply represented by a function that optionally takes props and returns a React element to be rendered to the page

Page 11: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

function Hello(props){ return <div>Hello {props.name}</div>}

The key thing that makes this type of component different from a class component is the lack of state and lifecycle methods. This is why functional components are also commonly referred to as stateless components.

Class ComponentComponents can also be written using ES6 classes instead of functions. Such components are called class components

class Hello extends Component{ render(){ return <div>Hello {this.props.name}</div> }}

Stateless vs Stateful components

Functional components

These components are purely presentational and are simply represented by a function that optionally takes props and returns a React element to be rendered to the page.

Generally, it is preferred to use functional components whenever possible because of their predictability and conciseness. Since, they are purely presentational, their output is always the same given the same props.

The functional components referred to as stateless.

=> Functional because they are basically functions

=> Stateless because they do not hold and/or manage state

=> Presentational because all they do is output UI elements

A functional component in it’s simplest form looks something like this:

Page 12: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

const Greeting = () => <h1>Hi, I’m a dumb component!</h1>;

Class Components

These components are created using ES6’s class syntax. They have some additional features such as the ability to contain logic (for example methods that handle onClick events), local state.

The class components referred to as stateful components.

=> Class because they are basically classes

=> Smart because they can contain logic

=> Stateful because they can hold and/or manage local state

=> Container because they usually hold/contain numerous other (mostly functional) components

A class component in its simplest form:

class Greeting extends React.Component { render(){ return <h1>Hi, I’m a smart component!</h1>; }}

Data Sharing between Components

There are two ways the components receive data:

1. Props2. States

1. Props

Props stand for properties. Props are React’s way of making components easily and dynamically customisable. They provide a way of passing properties/data down

Page 13: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

from one component to another, typically from a parent to a child component (unidirectional dataflow).

It’s important to note that props are read-only and that a component must never modify the props passed to it. As such, when a component is passed props as input, it should always return the same result for the same input.

Using Props with Functional Components:

An argument (props) is passed to the functional component. If a single argument is passed to the arrow function, the parentheses are unnecessary. Passing this argument lets the component know to expect some data to be passed to it. Within ReactDOM.render, the name you want rendered to the screen is passed in by specifying propName={propValue} within the component’s tag. There is no limit to how many props can be supplied to a component.

const Greeting = props => <h1>Hello {props.name}</h1>; ReactDOM.render( <Greeting name={‘cvr’}/>, document.getElementById('root') );

Using Props with Class Components:

Adding props to class components is a very similar process to the one used in the functional component. But the Props is not passed as an argument to the class. And the name attribute is accessed using this.props.name instead of props.name.

class Greeting extends React.Component { render(){ return <h1>Hello {this.props.name}</h1>; } }ReactDOM.render( <Greeting name={‘Cvr’}/>, document.getElementById('root') );

Page 14: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

2. State

State is a JavaScript object that stores a component’s dynamic data and determines the component’s behavior. Because state is dynamic, it enables a component to keep track of changing information in between renders and for it to be dynamic and interactive.

Generally, components take in props and render them. These are called stateless components. But they can also provide state which are used to store data or information about the component which can change over time. Such components are called stateful components. The change in state can happen as a response to user event or system event. In other words, state is the heart of every react component which determines how the component will behave and render. They are also responsible for making a component dynamic and interactive. Thus they must be kept as simple as possible.

The state can be accessed with this reference, e.g., this.state. You can access and print variables in JSX using curly braces {}. Similarly, you can render this.state inside render(). You must set a default state for the component else it will set to null.

State can only be used within a class component. If you anticipate that a component will need to manage state, it should be created as a class component and not a functional one.

Adding State to a Class Component

Adding state to the Greeting component involves defining within the class component, a constructor function that assigns the initial state using this.state.

class Greeting extends React.Component { constructor() { super(); // Define your state object here this.state = { name: ‘Jane Doe’ } }

Page 15: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

render(){ return <h1>Hello { this.state.name }</h1>; }}

ReactDom.render(<Greeting/>,document.getElementById(‘root’))

Adding super() is a must when using the constructor.

class MyComponent extends Component { constructor() { super(); this.state = { name: 'Maxx', id: '101' } } render() { setTimeout(()=>{this.setState({name:'Jaeha', id:'222'})},2000) return ( <div> <h1>Hello {this.state.name}</h1> <h2>Your Id is {this.state.id}</h2> </div> ); } }ReactDOM.render( <MyComponent/>, document.getElementById('root'));

Page 16: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

States vs Props

State vs. PropsA components state and props do share some common ground:

1. Both are plain JS objects2. Both can have default values3. Both should be accessed/read via this.props or this.state, but neither should

be given values this way. I.e., both are readonly when using this.

However they are used for different reasons and in different ways.

Props:

1. Props are passed into a component from above. Either a parent component or from the starting scope where React is originally rendered.

2. Props are intended as configuration values passed into the component. Think of them like arguments passed into a function (If you don't use JSX that is exactly what they are).

3. Props are immutable to the component receiving them. I.e., don't change props passed to a component from within the component

State:

1. State is a serializable representation of data (a JS object) at one point in time that typically is tied to UI

2. State should always start with a default value and then the state is mutated internally by the component using setState()

3. State can only be mutated by the component that contains the state, it is private in this sense.

4. Don't mutate the state of child components. A component should never have shared mutable state.

Page 17: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

5. State should only contain the minimal amount of data needed to represent UI's state, it should not contain computed data, other React components, or duplicated data from props.

6. State should be avoided if at all possible. I.e., stateless components are ideal, stateful components add complexity. The stateful component encapsulates all of the interaction logic, while the stateless components take care of rendering data in a declarative way."

React Component Lifecycle

React provides various methods which notify when a certain stage in the lifecycle of a component occurs. These methods are called the lifecycle methods. These lifecycle methods are not very complicated. You can think of these methods as specialized event handlers that are called at various points during a components life. You can even add your own code to these methods to perform various tasks. The lifecycle of the component is divided into 4 phases. They are:

Initialization: This is the stage where the component is constructed with the given Props and default state. This is done in the constructor of a Component Class.

Mounting: Mounting is the stage of rendering the JSX returned by the render method itself.

Updating: Updating is the stage when the state of a component is updated and the application is repainted.

Page 18: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

Unmounting: As the name suggests Unmounting is the final step of the component lifecycle where the component is removed from the page.

Now let us describe each phase and its corresponding functions.

Functions of each Phase of Lifecycle

1. Initialization: In this phase the developer has to define the props and initial state of the component this is generally done in the constructor of the component. The following code snippet describes the initialization process.

class Clock extends React.Component {     constructor(props)     {            // Calling the constructor of          // Parent Class React.Component         super(props);                    // Setting the initial state         this.state = { date : new Date() };      } }

2. Mounting: Mounting is the phase of the component lifecyle when the initialization of the component is completed and the component is mounted on the DOM and rendered for the first time in the webpage. Now React follows a default procedure in the Naming Conventions of this predefined functions where the functions containing “Will” represents before some specific phase and “Did” represents after the completion of that phase. Mounting phase consists of two such predefined functions as described below.

o componentWillMount() Function: As the name clearly suggests, this function is invoked right before the component is mounted on the DOM i.e. this function gets invoked once before the render() function is executed for the first time.

o componentDidMount() Function: Similarly as the previous one this function is invoked right after the component is mounted on the DOM i.e. this function gets invoked once after the render() function is executed for the first time.

Page 19: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

3. Updation: Updation is the phase where the states and props of a component are updated followed by some user events such as clicking, pressing a key on keyboard etc. The following are the descriptions of functions that are invoked at different points of Updation phase.

o componentWillRecieveProps() Function: This is a Props exclusive Function and is independent of States. This function is invoked before a mounted component gets its props reassigned. The function is passed the new set of Props which may or may not be identical to the original Props. Thus checking is a mandatory step in this regards.

o setState() Function: This is not particularly a Lifecycle function and can be invoked explicitly at any instant. This function is used to update the State of a component.

o shouldComponentUpdate() Function: By default, every state or props update re-render the page but this may not always be the desired outcome, sometimes it is desired that on updating the page will not be repainted. The shouldComponentUpdate() Function fulfills the requirement by letting React know whether the component’s output will be affected by the update or not. shouldComponentUpdate() is invoked before rendering an already mounted component when new props or state are being received. If returned false then the subsequent steps of rendering will not be carried out. This function can’t be used in case of forceUpdate(). The Function takes the new Props and new State as the arguments and returns whether to re-render or not.

o componentWillUpdate() Function: As the name clearly suggests, this function is invoked before the component is rerendered i.e. this function gets invoked once before the render() function is executed after the updation of State or Props.

o componentDidUpdate() Function: Similarly this function is invoked after the component is rerendered i.e. this function gets invoked once after the render() function is executed after the updation of State or Props.

4. Unmounting: This is the final phase of the lifeycle of the component that is the phase of unmounting the component from the DOM. The following function is the sole member of this phase.

o componentWillUnmount() Function: This function is invoked before the component is finally unmounted from the DOM i.e. this function gets invoked once before the component is removed from the page and this denotes the end of the lifecycle.

Page 20: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

import React from 'react'; import ReactDOM from 'react-dom';   class Test extends React.Component {     constructor(props)     {         super(props);         this.state = { hello : "World!" };     }       componentWillMount()     {         console.log("componentWillMount()");     }       componentDidMount()     {         console.log("componentDidMount()");     }       changeState()     {         this.setState({ hello : "Geek!" });     }       render()     {         return (             <div>             <h1>CVR College, Hello{ this.state.hello }</h1>             <h2>              <a onClick={this.changeState.bind(this)}>Press Here!</a>             </h2>             </div>);     }       shouldComponentUpdate(nextProps, nextState)     {         console.log("shouldComponentUpdate()");         return true;     }       componentWillUpdate()     {         console.log("componentWillUpdate()");     }       componentDidUpdate()     {         console.log("componentDidUpdate()");     }

Page 21: Setup and Installation  · Web viewReactJS. What is React? React is a JavaScript library - one of the most popular ones, with over 100,000 stars on GitHub. React is not a framework

}   ReactDOM.render(     <Test />,     document.getElementById('root'));