Copyright © 2017, edureka and/or its affiliates. All rights reserved. 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 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. COMPONENT’S BENEFITS 1. Entire application’s functionality is split into different components. 2. Each component generates HTML which is rendered by the DOM. COMPONENT’S ROLE
Copyright © 2017, edureka and/or its affiliates. All rights reserved. Search Bar Notifications Bar Add Post Chat Window Component Structure in Facebook
Copyright © 2017, edureka and/or its affiliates. All rights reserved. Component Structure using ES5 syntax . In ES5, we use React.createClass method to define React Component classes.1 4 Each component has a render function which tells the DOM what needs to be displayed on the screen. 2 Var keyword is used to declare variables whose values can be manipulated. 3 The method getInitialState is used to define initial state values. Component React.createClass Function() getInitalState
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. Explicit binding of “this” keyword is not needed. As of React 15.5, you will get a warning that React.createClass is deprecated and will be removed in react 16. No need to use any transpiler like Babel. We have to use commas to separate methods within classes.
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 Hover Double Click
Copyright © 2017, edureka and/or its affiliates. All rights reserved. React Components using ES5 Code example var Button =React.createClass( { getInitialState: function(){ return{ count:0 } }, propTypes: {name: React.PropTypes.string.isRequired} , We create a component class in React using createClass method. Var keyword is used to declare variables. The state variables are set initial values inside the getInitialState Method. Notice the comma which is added at the end of each function. It is a function used to validate the prop types.
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 }) }, render : function() { return( <div> <div classname="container"> Hello {this.props.name} </div> <button onClick={this.Increcount}> Count:{this.state.count} </button> </div> ) } }); This is a function to increment the counter Each component in react has a render function which returns HTML to the DOM “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 } }, Increcount : function() { this.setState({ count: this.state.count + 1 }) }, render : function() { return( <div> <button onDoubleClick={this.Increcount}> Count:{this.state.count} </button> </div> ) } }); 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.
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 }) }, render : function() { return( <div> <button onMouseMove={this.Increcount}> Count:{this.state.count} </button> </div> ) } }); Notice as the number of components increase, the complexity in ES5 increases. the state values and functions are being used here redundantly.
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> ); } }); ReactDOM.render(<Compo />,document.getElementById('root')); This is where, we render our button components.
Copyright © 2017, edureka and/or its affiliates. All rights reserved. Benefits of ES6 Components Compact JavaScript Centric Use of Const, Let 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. • No need to use commas (,) to separate functions. • Stateless components can be converted to pure functions leading to a minimal code size. 2 1 Compact Javascript Centric Use of Const, let Pure functions
Copyright © 2017, edureka and/or its affiliates. All rights reserved. Benefits of ES6 Components ES6 adopts a JavaScript Centric approach. This can be observed from below:- Compact Javascript Centric Use of Const, let Pure functions Benefits of ES6 Components Passing state values inside the constructor. As the Component is now a function, PropTypes are a property on the function itself. . 1 2 Compact Javascript Centric Use of Const, let Pure functions constructor(props){ super(props) this.state= {count:0}} Button.propTypes = { name: React.PropTypes.string.isRequired, };
Copyright © 2017, edureka and/or its affiliates. All rights reserved. ➢ The global scoped var keyword in ES5 is replaced with const and let which are block scoped in ES6. ➢ We use const for constant values; let is used for variable values. ➢ Const supports immutablility(constant). (Data that is critical to an organization and should not be changed by a new employee). Benefits of ES6 Components Compact Javascript Centric Use of Const, let Pure functions Intern tries to change value of const But it’s a failed attempt as const is immutable
Copyright © 2017, edureka and/or its affiliates. All rights reserved. Benefits of ES6 Components Stateless Functional Component . Prop:count Prop:name UI 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 Pure functions
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 let Basecomp = (Basic_comp) => class extends React.Component{ constructor(props){ super(props) this.state= {count:0} this.Increcount=this.Increcount.bind(this);}//end Constructor Increcount () { this.setState({ count: this.state.count + 1 }) } We create a class based component which extends the Component class. Let is used to declare variables. State values are passed inside the constructor. We need to call super() inorder to access ‘prop’ values. 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> ); } } const Button = (props) => { return ( <div> <div>Hello,{props.name} </div> <button onClick={props.increment} > Count:{props.count} </button> </div> )} Button.propTypes = { name: React.PropTypes.string.isRequired, }; Notice how the function keyword is dropped in render() We use object spread {…} operator to load all state variables at once Const is used to declare constants Notice how, we pass the event handler as a prop to the onclick event 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) const Hoverbtn= (props) =>{ return( <button onMouseMove={props.increment}> Count:{props.count} </button> ) } const Dbtn= (props) =>{ return( <button onDoubleClick={props.increment}> Count:{props.count} </button> ) } ‘Hoverbtn’ increments its counter when you hover the cursor over it . 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. ‘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 used a higher order component to wrap around the pure functional component. We make use of another pure function to render the final output. 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); const Comp=()=>{ return ( <div> <Compclick/> <Compdclick/> <Compohover/> </div> ) } 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 class Board extends React.Component { constructor() { super(); this.state = { squares: Array(9).fill(null), xIsNext: true, }; } We push state up into the Board component and fill the squares with null values for beginning. 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. The Board component can tell each Square what to display, this is why state should reside within Board component.
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]) { return squares[a]; } } return null; } 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 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 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, }); } handleclick() returns either the winner or the next player. We manipulate state variable XIsNext to Return the player. • 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.
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 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> ); } We now define our third component ‘Game’ Which is used to render the ‘Board’ component. Also we include some div containers to put the squares in place.
Copyright © 2017, edureka and/or its affiliates. All rights reserved. Component Structure using ES5 syntax React Components using ES5 Code example Tic Tac Toe With ReactReact Components using ES6 Code exampleBenefits of ES6 Components Pros and Cons of ES5 Syntax Summary Slide
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.

React ES5 to ES6 | React ES5 vs ES6 | React Tutorial for Beginners | React online Training | Edureka

  • 2.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. 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
  • 3.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. Introduction to React Components “Everything in React is a component”- said every JS developer 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. COMPONENT’S BENEFITS 1. Entire application’s functionality is split into different components. 2. Each component generates HTML which is rendered by the DOM. COMPONENT’S ROLE
  • 4.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. Search Bar Notifications Bar Add Post Chat Window Component Structure in Facebook
  • 5.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. Component Structure using ES5 syntax . In ES5, we use React.createClass method to define React Component classes.1 4 Each component has a render function which tells the DOM what needs to be displayed on the screen. 2 Var keyword is used to declare variables whose values can be manipulated. 3 The method getInitialState is used to define initial state values. Component React.createClass Function() getInitalState
  • 6.
    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. Explicit binding of “this” keyword is not needed. As of React 15.5, you will get a warning that React.createClass is deprecated and will be removed in react 16. No need to use any transpiler like Babel. We have to use commas to separate methods within classes.
  • 7.
    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 Hover Double Click
  • 8.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. React Components using ES5 Code example var Button =React.createClass( { getInitialState: function(){ return{ count:0 } }, propTypes: {name: React.PropTypes.string.isRequired} , We create a component class in React using createClass method. Var keyword is used to declare variables. The state variables are set initial values inside the getInitialState Method. Notice the comma which is added at the end of each function. It is a function used to validate the prop types.
  • 9.
    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 }) }, render : function() { return( <div> <div classname="container"> Hello {this.props.name} </div> <button onClick={this.Increcount}> Count:{this.state.count} </button> </div> ) } }); This is a function to increment the counter Each component in react has a render function which returns HTML to the DOM “this” keyword is used to refer to the props value.
  • 10.
    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 } }, Increcount : function() { this.setState({ count: this.state.count + 1 }) }, render : function() { return( <div> <button onDoubleClick={this.Increcount}> Count:{this.state.count} </button> </div> ) } }); 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.
  • 11.
    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 }) }, render : function() { return( <div> <button onMouseMove={this.Increcount}> Count:{this.state.count} </button> </div> ) } }); Notice as the number of components increase, the complexity in ES5 increases. the state values and functions are being used here redundantly.
  • 12.
    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> ); } }); ReactDOM.render(<Compo />,document.getElementById('root')); This is where, we render our button components.
  • 13.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. Benefits of ES6 Components Compact JavaScript Centric Use of Const, Let Pure Functions
  • 14.
    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. • No need to use commas (,) to separate functions. • Stateless components can be converted to pure functions leading to a minimal code size. 2 1 Compact Javascript Centric Use of Const, let Pure functions
  • 15.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. Benefits of ES6 Components ES6 adopts a JavaScript Centric approach. This can be observed from below:- Compact Javascript Centric Use of Const, let Pure functions Benefits of ES6 Components Passing state values inside the constructor. As the Component is now a function, PropTypes are a property on the function itself. . 1 2 Compact Javascript Centric Use of Const, let Pure functions constructor(props){ super(props) this.state= {count:0}} Button.propTypes = { name: React.PropTypes.string.isRequired, };
  • 16.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. ➢ The global scoped var keyword in ES5 is replaced with const and let which are block scoped in ES6. ➢ We use const for constant values; let is used for variable values. ➢ Const supports immutablility(constant). (Data that is critical to an organization and should not be changed by a new employee). Benefits of ES6 Components Compact Javascript Centric Use of Const, let Pure functions Intern tries to change value of const But it’s a failed attempt as const is immutable
  • 17.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. Benefits of ES6 Components Stateless Functional Component . Prop:count Prop:name UI 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 Pure functions
  • 18.
    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
  • 19.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. React Components using ES6 Code example let Basecomp = (Basic_comp) => class extends React.Component{ constructor(props){ super(props) this.state= {count:0} this.Increcount=this.Increcount.bind(this);}//end Constructor Increcount () { this.setState({ count: this.state.count + 1 }) } We create a class based component which extends the Component class. Let is used to declare variables. State values are passed inside the constructor. We need to call super() inorder to access ‘prop’ values. We explicitly bind functions inside the constructor.
  • 20.
    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> ); } } const Button = (props) => { return ( <div> <div>Hello,{props.name} </div> <button onClick={props.increment} > Count:{props.count} </button> </div> )} Button.propTypes = { name: React.PropTypes.string.isRequired, }; Notice how the function keyword is dropped in render() We use object spread {…} operator to load all state variables at once Const is used to declare constants Notice how, we pass the event handler as a prop to the onclick event Here, propTypes is seen as a built-in property instead of a return value
  • 21.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. React Components using ES6 Code example(Continued) const Hoverbtn= (props) =>{ return( <button onMouseMove={props.increment}> Count:{props.count} </button> ) } const Dbtn= (props) =>{ return( <button onDoubleClick={props.increment}> Count:{props.count} </button> ) } ‘Hoverbtn’ increments its counter when you hover the cursor over it . 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. ‘Dbtn ’ is used to increment counter on each double click.
  • 22.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. React Components using ES6 Code example(Continued) We have used a higher order component to wrap around the pure functional component. We make use of another pure function to render the final output. 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); const Comp=()=>{ return ( <div> <Compclick/> <Compdclick/> <Compohover/> </div> ) } ReactDOM.render( <Comp/>,document.getElementById('root'));
  • 23.
    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.
  • 24.
    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.
  • 25.
    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.
  • 26.
    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.
  • 27.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. Tic Tac Toe In React: Code Explained class Board extends React.Component { constructor() { super(); this.state = { squares: Array(9).fill(null), xIsNext: true, }; } We push state up into the Board component and fill the squares with null values for beginning. 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. The Board component can tell each Square what to display, this is why state should reside within Board component.
  • 28.
    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]) { return squares[a]; } } return null; } 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 We return null if any condition fails else we return ‘X’ or ‘O’
  • 29.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. Tic Tac Toe In React: Code Explained 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, }); } handleclick() returns either the winner or the next player. We manipulate state variable XIsNext to Return the player. • 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.
  • 30.
    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.
  • 31.
    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 !
  • 32.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. Tic Tac Toe In React: Code Explained 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> ); } We now define our third component ‘Game’ Which is used to render the ‘Board’ component. Also we include some div containers to put the squares in place.
  • 33.
    Copyright © 2017,edureka and/or its affiliates. All rights reserved. Component Structure using ES5 syntax React Components using ES5 Code example Tic Tac Toe With ReactReact Components using ES6 Code exampleBenefits of ES6 Components Pros and Cons of ES5 Syntax Summary Slide
  • 34.
    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.