360 likes | 585 Views
( ReactJS Training - https://www.edureka.co/reactjs-redux-... )<br>This Edureka React tutorial on ES5 to ES6 Refactoring will help you in understanding the current syntax being used in React and what new features you can use in the upgraded version. This video helps you to learn following topics:<br><br>1. Introduction to React Components<br>2. Component structure in ES5<br>3. ES5 with pros, cons and code example<br>4. Benefits to ES6<br>5. ES6 restructuring of code example<br>6. Building Tic tac Toe game in React using ES6
E N D
Agenda i. Introduction to React components ii. Component structure using ES5 iii. ES5 with pros, cons and code example iv. Benefits of ES6 v. ES6 restructuring of code example vi. Building Tic Tac Toe game in React using ES6 Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Introduction to React Components “Everything in React is a component”- said every JS developer COMPONENT’S ROLE 1. Entire application’s functionality is split into different components. 2. Each component generates HTML which is rendered by the DOM. COMPONENT’S BENEFITS 1. Components enable the use of a Modular approach, where pieces of code are isolated thus enhancing Readability. 2. While refreshing the page, only the components in which changes occur are updated; this boosts optimization. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Component Structure in Facebook Search Bar Notifications Bar Add Post Chat Window Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Component Structure using ES5 syntax React.createClass Function() getInitalState Component . 1 In ES5, we use React.createClass method to define React Component classes. 2 Var keyword is used to declare variables whose values can be manipulated. 3 The method getInitialState is used to define initial state values. 4 Each component has a render function which tells the DOM what needs to be displayed on the screen. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Pros and Cons of ES5 Syntax Pros Cons Browser support is a huge plus. ( IE-11 Supports all major features of ES5 ). Code is lengthy, hence affects readability and maintainability. As of React 15.5, you will get a warning that React.createClass is deprecated and will be removed in react 16. Explicit binding of “this” keyword is not needed. We have to use commas to separate methods within classes. No need to use any transpiler like Babel. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Building Our Application ▪ We will demonstrate React component structure using ES5 syntax in our basic application. ▪ In our example, we create three buttons, one each for mouse hover , mouse single click ,mouse double click respectively. ▪ These buttons increment their counter when a particular mouse gesture is made and the count is displayed. ▪ We also demonstrate use of props to display a message on the screen. Single Click Double Click Hover Copyright © 2017, edureka and/or its affiliates. All rights reserved.
React Components using ES5 Code example We create a component class in React using createClass method. var Button =React.createClass( { getInitialState: function(){ return{ count:0 } }, propTypes: {name: React.PropTypes.string.isRequired} Var keyword is used to declare variables. The state variables are set initial values inside the getInitialState Method. It is a function used to validate the prop types. , Notice the comma which is added at the end of each function. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
React Components using ES5 Code example(Continued) Increcount : function() { this.setState({ count: this.state.count + 1 }) }, This is a function to increment the counter Each component in react has a render function which returns HTML to the DOM render : function() { return( <div> <div classname="container"> Hello {this.props.name} </div> <button onClick={this.Increcount}> Count:{this.state.count} </button> </div> “this” keyword is used to refer to the props value. ) } }); Copyright © 2017, edureka and/or its affiliates. All rights reserved.
React Components using ES5 Code example(Continued) var Dbtn =React.createClass ( { getInitialState: function(){ return{ count:0 } }, In ES5, we create more component classes for each button component and pass state values to each. We define our ‘increcount’ function again inside each button component. Increcount : function() { this.setState({ count: this.state.count + 1 }) }, render : function() { return( <div> <button onDoubleClick={this.Increcount}> Count:{this.state.count} </button> </div> ) } }); Copyright © 2017, edureka and/or its affiliates. All rights reserved.
React Components using ES5 Code example(Continued) var Hoverbtn =React.createClass( { getInitialState: function(){ return{ count:0 } }, Increcount : function() { this.setState({ count: this.state.count + 1 }) }, Notice as the number of components increase, the complexity in ES5 increases. the state values and functions are being used here redundantly. render : function() { return( <div> <button onMouseMove={this.Increcount}> Count:{this.state.count} </button> </div> ) } }); Copyright © 2017, edureka and/or its affiliates. All rights reserved.
React Components using ES5 Code example(Continued) We define another component ‘Compo’ which is used to render output to the DOM. var Compo =React.createClass({ render:function(){ return( <div> <div> <Button name="shiva" /> </div> <div> <Dbtn /> </div> <div> <Hoverbtn /> </div> </div> ); This is where, we render our button components. } }); ReactDOM.render(<Compo />,document.getElementById('root')); Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Benefits of ES6 Components JavaScript Centric Use of Const, Let Compact Pure Functions Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Benefits of ES6 Components The addition of arrow functions ( also known as Fat arrow => ) supports many purposes 1. The function keyword is dropped. 2. It helps in auto binding of this keyword in functions 3. You can remove curly braces and return keyword if there is a single line of logic. 1 Compact Javascript Centric . Use of Const, let Pure functions • No need to use commas (,) to separate functions. • Stateless components can be converted to pure functions leading to a minimal code size. 2 Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Benefits of ES6 Components Benefits of ES6 Components ES6 adopts a JavaScript Centric approach. This can be observed from below:- Compact Compact Passing state values inside the constructor. 1 Javascript Centric Javascript Centric constructor(props){ super(props) this.state= {count:0}} Use of Const, let Use of Const, let As the Component is now a function, PropTypes are a property on the function itself. 2 Pure functions Pure functions . Button.propTypes = { name: React.PropTypes.string.isRequired, }; Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Benefits of ES6 Components ➢ The global scoped var keyword in ES5 is replaced with const and let which are block scoped in Compact ES6. ➢ We use const for constant values; let is used for variable values. Javascript Centric ➢ Const supports immutablility(constant). Use of Const, let (Data that is critical to an organization and should not be changed by a new employee). Intern tries to change value of const Pure functions But it’s a failed attempt as const is immutable Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Benefits of ES6 Components . In React with ES6, we are able to abstract state away from our functional components. For this we utilize stateless functional components. Now its as simple as Props In and UI out. Compact Javascript Centric Use of Const, let Stateless Functional Component Prop:count Pure functions UI Prop:name Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Demo Now let’s see a demonstration of how to rebuild our components using ES6 Syntax Copyright © 2017, edureka and/or its affiliates. All rights reserved.
React Components using ES6 Code example We create a class based component which extends the Component class. let Basecomp = (Basic_comp) => class extends React.Component{ constructor(props){ super(props) this.state= {count:0} this.Increcount=this.Increcount.bind(this);}//end Constructor Let is used to declare variables. State values are passed inside the constructor. We need to call super() inorder to access ‘prop’ values. Increcount () { this.setState({ count: this.state.count + 1 }) } We explicitly bind functions inside the constructor. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
React Components using ES6 Code example(Continued) render() { return( <div> <Basic_comp {...this.state} increment ={this.Increcount} name="shiva"/> </div> Notice how the function keyword is dropped in render() We use object spread {…} operator to load all state variables at once ); } } const Button = (props) => { return ( <div> <div>Hello,{props.name} </div> <button onClick={props.increment} > Count:{props.count} </button> </div> )} Const is used to declare constants Notice how, we pass the event handler as a prop to the onclick event Button.propTypes = { name: React.PropTypes.string.isRequired, }; Here, propTypes is seen as a built-in property instead of a return value Copyright © 2017, edureka and/or its affiliates. All rights reserved.
React Components using ES6 Code example(Continued) We create two more button components using pure functions and call them using the same constructor. This is how we abstract state away from our stateless components in ES6. ‘Hoverbtn’ increments its counter when you hover the cursor over it . const Hoverbtn= (props) =>{ return( <button onMouseMove={props.increment}> Count:{props.count} </button> ) } const Dbtn= (props) =>{ return( <button onDoubleClick={props.increment}> Count:{props.count} </button> ) ‘Dbtn ’ is used to increment counter on each double click. } Copyright © 2017, edureka and/or its affiliates. All rights reserved.
React Components using ES6 Code example(Continued) We have created our Button Components as pure Stateless functions which is a unique option in ES6. let Compohover= Basecomp(Hoverbtn); let Compclick=Basecomp(Button); let Compdclick=Basecomp(Dbtn); We have used a higher order component to wrap around the pure functional component. const Comp=()=>{ return ( <div> <Compclick/> <Compdclick/> <Compohover/> </div> ) We make use of another pure function to render the final output. } ReactDOM.render( <Comp/>,document.getElementById('root')); Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Demo Now that we have learnt about ES6 features, let’s see a demonstration of how to build a Tic Tac Toe Game With React. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Tic Tac Toe With React ▪ In this section, we’ll take help of these ES6 features : arrow functions, classes, let and const statements. ▪ We have three components: Board, Square and Game. ▪ For each player’s turn we shift between ‘X‘ and ‘O’. ▪ We will need to predict a winner based on each player’s moves. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Tic Tac Toe In React: Explained We start with 9 empty squares which are rendered by the board component. When the first player clicks on a square, the component re- renders this.state.value to 'X’. So he’ll see an ‘X’ in the grid. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Tic Tac Toe In React: Code Explained function Square(props) { return ( <button className="square" onClick={props.onClick}> {props.value} </button> ); } We use a pure function(Stateless) to define the Square component which: 1. Receives prop values from its parent board. 2. It notifies Board when it is clicked. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Tic Tac Toe In React: Code Explained The Board component can tell each Square what to display, this is why state should reside within Board component. We push state up into the Board component and fill the squares with null values for beginning. class Board extends React.Component { constructor() { super(); this.state = { squares: Array(9).fill(null), xIsNext: true, }; } This is a Boolean value which is a pointer to switch between players renderSquare(i) { return ( <Square value={this.state.squares[i]} onClick={() => this.handleClick(i)} /> ); } Now we're passing down two props from Board to Square: value and onClick. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Tic Tac Toe In React: Code Explained function calculateWinner(squares) { const lines = [ [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]; for (let i = 0; i < lines.length; i++) { const [a, b, c] = lines[i]; if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) { We need a function to find a winner We pass all the square combinations in an array. We use a for loop to identify matching squares return squares[a]; } } return null; } We return null if any condition fails else we return ‘X’ or ‘O’ Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Tic Tac Toe In React: Code Explained • Now that we have seen the ‘CalculateWinner Function()’, lets get back to the board component where we define handleClick event handler. Board passed onClick={() => this.handleClick(i)} to Square, so, when called, it runs this.handleClick(i) on the Board. • handleclick() returns either the winner or the next player. handleClick(i) { const squares = this.state.squares.slice(); if (calculateWinner(squares) || squares[i]) { return; } squares[i] = this.state.xIsNext ? 'X' : 'O'; this.setState({ squares: squares, xIsNext: !this.state.xIsNext, }); } We manipulate state variable XIsNext to Return the player. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Tic Tac Toe In React: Code Explained render() { const winner = calculateWinner(this.state.squares); let status; if (winner) { status = 'Winner: ' + winner; } else { status = 'Next player: ' + (this.state.xIsNext ? 'X': 'O'); } We use ES6 ‘let’ to declare a variable ‘status’ which prints the winner in case a player wins or indicates the next player’s turn. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Tic Tac Toe In React: Code Explained return ( <div> <div className="status">{status}</div> <div className="board-row"> {this.renderSquare(0)} {this.renderSquare(1)} {this.renderSquare(2)} </div> <div className="board-row"> {this.renderSquare(3)} {this.renderSquare(4)} {this.renderSquare(5)} </div> <div className="board-row"> {this.renderSquare(6)} {this.renderSquare(7)} {this.renderSquare(8)} </div> </div> ); Inside the Board’s render function we will be returning the 9 squares using the renderSquare method. Now, all we need is to make three rows, include some CSS and we‘re good to go ! } } Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Tic Tac Toe In React: Code Explained We now define our third component ‘Game’ Which is used to render the ‘Board’ component. class Game extends React.Component { render() { return ( <div className="game"> <div className="game-board"> <Board /> </div> <div className="game-info"> <div>{/* status */}</div> </div> </div> ); } Also we include some div containers to put the squares in place. Copyright © 2017, edureka and/or its affiliates. All rights reserved.
Summary Slide Component Structure using ES5 syntax React Components using ES5 Code example Pros and Cons of ES5 Syntax Benefits of ES6 Components React Components using ES6 Code example Tic Tac Toe With React Copyright © 2017, edureka and/or its affiliates. All rights reserved.
WebDriver vs. IDE vs. RC ➢ Data Warehouse is like a relational database designed for analytical needs. ➢ It functions on the basis of OLAP (Online Analytical Processing). ➢ It is a central location where consolidated data from multiple locations (databases) are stored. Copyright © 2017, edureka and/or its affiliates. All rights reserved.