Setup and Installation
ReactJSWhat 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 InstallationThere are a few ways to set up React.1. Static HTML FileThis 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 APIReact DOM - adds DOM-specific methodsBabel - a JavaScript compiler that lets us use ES6+ in old browsersThe 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> <meta charset="utf-8" /> <title>Hello React!</title> <script src=""></script> <script src=""> </script> <script src=""></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 ponent { //...}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 ponent { render() { return ( //... ); }}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 ponent { 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=""></script> <script src=""></script> <script src=""></script> </head> <body> <div id="root"></div> </body></html> <script type="text/babel"> class App extends ponent { 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.2. Create React AppThe 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-tutorialOnce that finishes installing, move to the newly created directory and start the project.>cd react-tutorial>npm startOnce you run this command, a new window will popup at localhost:3000 with your new React app.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"> <h1>Hello, React!</h1> </div> ) }}ReactDOM.render(<App />, document.getElementById('root'))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 DOMToday, 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 SPAIf 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.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 onServer events: When an application receives data or an error from a server, among otherswhen 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:Whenever the state of your data model changes, the virtual DOM and React will rerender your UI to a virtual DOM representation.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.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.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 ponents 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 pagefunction 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 componentsclass Hello extends Component{ render(){ return <div>Hello {this.props.name}</div> }}Stateless vs Stateful componentsFunctional componentsThese 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 elementsA functional component in it’s simplest form looks something like this:const Greeting = () => <h1>Hi, I’m a dumb component!</h1>;Class ComponentsThese 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) componentsA class component in its simplest form:class Greeting extends ponent { render(){ return <h1>Hi, I’m a smart component!</h1>; }}Data Sharing between ComponentsThere are two ways the components receive data:PropsStates1. PropsProps stand for properties. Props are React’s way of making components easily and dynamically customisable. They provide a way of passing properties/data down 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 ponent { render(){ return <h1>Hello {this.props.name}</h1>; } }ReactDOM.render( <Greeting name={‘Cvr’}/>, document.getElementById('root') );2. StateState 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 ComponentAdding 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 ponent { constructor() { super(); // Define your state object here this.state = { name: ‘Jane Doe’ } } 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'));States vs PropsState vs. PropsA components state and props do share some common ground:Both are plain JS objectsBoth can have default valuesBoth 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:Props are passed into a component from above. Either a parent component or from the starting scope where React is originally rendered.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).Props are immutable to the component receiving them. I.e., don't change props passed to a component from within the componentState:State is a serializable representation of data (a JS object) at one point in time that typically is tied to UIState should always start with a default value and then the state is mutated internally by the component using setState()State can only be mutated by the component that contains the state, it is private in this sense.Don't mutate the state of child components. A component should never have shared mutable state.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.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 LifecycleReact 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.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 LifecycleInitialization: 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 ponent { ????constructor(props) ????{??? ????????// Calling the constructor of? ????????// Parent Class ponent ????????super(props);? ??????????????????// Setting the initial state ????????this.state = { date : new Date() };? ????} } 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. 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 ponentDidMount() 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.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. 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. 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.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 ponentWillUpdate() 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 ponentDidUpdate() 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.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. 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. import React from 'react'; import ReactDOM from 'react-dom'; ??class Test extends ponent { ????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()"); ????} } ??ReactDOM.render( ????<Test />, ????document.getElementById('root')); ................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related searches
- xfinity free installation promo
- installation and operation qualification
- office setup student and home have key
- equipment installation qualification
- installation qualification template
- installation qualification requirements
- software installation qualification
- installation qualification wiki
- installation qualification checklist
- installation qualification protocol template
- installation qualification sop
- equipment installation qualification template