SlideShare a Scribd company logo
ReactJS + Flux + JSX + Jest
Eswara K Palakollu@Sapient
Learn Isomorphic React and Flux Life cycle
in detail.
ReactJS
What is React?
• Reactjs is a java script library for building composable, maintainable and
testable user interfaces.
• React covers just view ‘V’ in MVC pattern.
How does React work?
React abstracts application DOM and
maintains Virtual DOM in memory for
handling in-page interactions and updates
from server.
React compares previous state of Virtual
DOM with new state of Virtual DOM and
updates physical DOM with the changed
elements.
Physical DOM always reflect up to date
application state and react updates virtual
DOM whenever application state changes
and which internally updates physical
DOM.
React Virtual DOM
Physical DOM
Application
Events
Events
Only changed elements
Why React?
• Fast
• Unidirectional data flow from parent components to child components.
• Isomorphic
• Easy to debug & testable
• SPA friendly.
• Can co-exist with other frameworks and easy to try it out.
• Use JSX with familiar HTML like syntax for writing react applications.
React in M’V’C
React at client side (Non-SEO / SPA)
React at server
side (SEO)
JSX
• JSX is a ECMASCRIPT syntactic extension similar to HTML and XML.
• JSX helps to write secure java script with familiar HTML like syntax.
• JSX transpilers help to compile JSX syntactic code into pure java script for
execution on browsers.
• React JSX transpiler can be used to compile react JSX code into pure java
script for execution.
• <ProductImage href=“image.jpeg”></ ProductImage>
JSX – Syntax
• Use Upper case for custom tags <ProductImage><image
href=“./image.jpeg”/> </ProductImage>
• Use lower case for html tags <image href=“./image.jpeg” />
• Self Closing - <ProductImage href=“./image.jpeg” />
• Child elements - <Product><ProductImage href=“./image.jpeg” /> </Product>
• Pass properties - <ProductImage href=“./image.jpeg” />
• Spread attributes <ProductImage {…this.props} />
• Attribute expression <ProductImage href={this.props.href} />
Get hands dirty.
React first application
Tools and packages
• Using ECMA6 compatible REACT API and differences to ECMA5 are called
out later.
• react, react-addons-test-utils
• react-dom, react-dom/server
• react-router
• flux
• babel frameworks
• jest – unit testing
• webpack
React APIs
• React.Component API covers component life cycle methods discussed in the
coming sections.
• ReactDOM – This package provides DOM specific methods such as
rendering DOM at client side and server side for SEO benefits.
 render() method will be the primary and mandatory method used in this API for
rendering components on client side.
 renderToString() [react-dom/server] method will be useful to render the component
on server side and send HTML to client side for client side binding and event
listeners.
 findDOMNode() method is useful for reading DOM elements. Mostly refs and event
listeners will cover most of the needs.
 renderToStaticMarkup() [react-dom/server] method is useful for sending pure html
to client without any react hooks.
 unmountComponentAtNode() method will serve opposite of render() method to
unmount the rendered component from DOM.
React Component life cycle
React Component life cycle explained
• getDefaultProps()
 This method is called only once and shared between instances of react component for
better performance.
 Don’t access or update component’s state in this method as this method is called once and
shared between instances.
• getInitialState()
 This method is called every time component is initialized for the first time. In ES6, initial
state has to be set in constructor() method as this method is not available.
 Set component’s initial state for rendering.
 Invoke ajax if data to be retrieved from server on page load.
• Mounting: componentWillMount()
 This method is called just before initial rendering.
 Invoke third party or server call and update components state if necessary.
 Updating state will not re-render the component.
 Don’t attempt to read physical DOM in this method as component is not yet mounted.
React Component life cycle explained
• Mounting: componentDidMount()
 This method is called just after initial rendering.
 Integrate with third party or AJAX calls to server or analytics etc.
 Access refs and DOM elements in this method.
• Updating: componentWillReceiveProps(nextProps)
 Updating component state / props will trigger re-rendering of View.
 Updating component state / pros is allowed here.
 Updating props from parent can trigger re-rendering of updated child component.
• Updating: shouldComponentUpdate(nextProps,nextState)
 Return false if rendering of changed state / props is not needed.
 By default this method returns true always unless there is a performance reason to
return try by comparing previosProps and nextProps
 If it returns true componentWillUpdate() and componentDidUpdate() will be called
otherwise not called.
React Component life cycle explained
• Updating: componentWillUpdate(nextProps, nextState)
 This method is invoked before rendering when new props or state being received.
 Updating state is not allowed in this method. Use componentWillReceiveProps() for
updating state.
• Updating: componentDidUpdate(prevProps, prevState)
 This method is invoked right after component nextProps rendered successfully.
 DOM can be accessed in this method.
 Third party calls or ajax server calls can be invoked in this method.
 Application state / props can be accessed and updated in this method.
Unidirectional data flow in React
• In react, data flows in one direction from parent to child components using
props.
• React renders data using component state and the properties sent by parent
react component to it.
• Component state is maintained by this.state variable and initialised in
constructor() aka getIntitialState() in ES5 version.
• Properties are usually passed to the component by its parent and this.props
will hold all the properties passed by parent.
• getDefaultProperties() will be used to initialise the properties and it is
invoked only once and shared between instances.
Get hands dirty.
Application State
Application state
• React maintains application state at component level and sends required
state attributes to child components via props.
• Every time application state changes the changed state is passed to child
components to update the views again.
• this.state – holds the component state received from server or set by
component.
• this.props – holds the properties sent by its parent and any callbacks needed
to call for updating state in parent that will trigger updated props to this
component for updating view again.
this.state = {title: ‘I am the initial state’};
• State (this.state) in react refers to component state that will be rendered in View
by ReactDOM.
• State can be changed by calling this.setState(). React rerenders the component
when the state is updated.
 this.setState({title: ‘I am the updated state’});
 this.setState({title: ‘I am the updated state with callback’,function(){});
• State is private to the component unlike this.props and it can be managed by
using react life cycle methods.
• While mounting use componentWillMount() method to update state before initial
rendering.
• While updating the state after initial rendering, use
componentWillReceiveProps() before re-rendering or componentDidUpdate() for
accessing and updating DOM after rendering based on user or server interaction.
• Never assign state to this.state directly instead use this.setState() as updating
this.state doesn’t invoke react life cycle correctly.
this.props
• React props are owned and maintained by parent component.
• Parent component sends state to child react components as properties for
rendering.
• Child tags or html content between opening and closing tags can be accessed
using this.props.children.
• <ProductImage href=“image.jpeg”> <img src=“image.jpeg”></img>
</ProductImage>
• this.props.children will give <img src=“image.jpeg”></img> tag.
• When this.props are updated, parent broadcasts the change to all its child
tags that will invoke componentWillReceiveProps() life cycle method.
rest and spread props {a,b,…rest}
• Take advantage of ECMA6 arrays destructuring to use rest or spread the
properties sent by parent.
• let {href , title} = this.props; //spread the required attributes from props
• let {href , title, …more} = this.props; //…more holds the rest of the attributes
apart from spread attributes href and title.
render(){return <h1>hello</h1>)}
• render() is the must have function and only mandatory method in every
react component.
• render must return HTML content or another react child component for
rendering.
• Render can only render one element for now due to syntactic issues with
java script. If multiple elements need to be rendered, surround all the
elements with a div or any other element as per the need.
render(){
return {
<div> <h1>Product Description</h1>
<p>print product description here.</p>
<ProductMoreDetails id={this.props.product.id} />
</div>
}
}
Get hands dirty.
refs
• React provide refs (references) to access DOM after component is displayed.
• Avoid using refs as react manages keep component displayed correctly at all
times and there shouldn’t be any need to manipulate DOM manually.
• Usually accessing DOM may not be required given that react manages updating
the DOM when props are propagated from parent or state changes.
• In some cases other parts of the bigger application may need to reference DOM
to further action.
• this.refs.
render(){
return {
<div> <h1>Product Description</h1>
<p ref=“productDescription”>print product description here.</p>
</div>
}
}
key attribute
• Key attribute optimizes rendering of ordered or unordered list of elements on the page.
• If a dropdown has 20 elements and one of the element changed. React will compare the
difference using Virtual DOM which eventually end of updating all the items in the
dropdown.
• Key attribite will help react to identify the changes correctly and update only the changed
elements instead of re-rendering unchanged elements.
• <ul>
• <li key=“sku1”>SKU1</li>
• <li key=“sku2”>SKU2</li>
• <li key=“sku3”>SKU3</li>
• <li key=“sku4”>SKU4</li>
• </ul>
• React removes “sku1” and inserts “sku5” without touching other elements in the list.
<ul>
<li key=“sku5”>SKU5</li>
<li key=“sku2”>SKU2</li>
<li key=“sku3”>SKU3</li>
<li key=“sku4”>SKU4</li>
</ul>
Other attributes
• forceUpdate() – It forced react to render without calling
shouldComponentUpdate() method.
• propTypes() – It allows to type check input prop types before
getDefaultProps() is called. For performance reasons this method should
only be checked in development environment.
ECMA5 vs ECMA6
• React latest 0.14.x supports ECMA6 and few life cycle methods have
deprecated from API. I have omitted the api methods that may be removed
completely from ECMA6 version.
• ECMA5 ES2015(aka ECMA6)
React.createClass() used for creating
react component classes.
var App = React.createClass({
});
Extend React.Component class to
create custom components.
class App extends
React.Component{}
Deprecated methods to stay way
from using:
replaceState()
isMounted()
getDOMNode()
isMounted()
setProps()
replaceProps()
React SEO – Server side rendering
• Isomorphic react provides SEO support for compiling HTML at server side
and bid the non-seo components at client side.
• ReactDOM API provides functionality for executing react component on
server side.
React DOM API
• ReactDOM – This package provides DOM specific methods such as
rendering DOM at client side and server side for SEO benefits.
 render() method will be the primary method used in this API for rendering
components on client side.
 renderToString() [react-dom/server] method will be useful to render the component
on server side and send HTML to client side for client side binding and event
listeners.
 findDOMNode() method is useful for reading DOM elements. Mostly refs and event
listeners will cover most of the needs.
 renderToStaticMarkup() [react-dom/server] method is useful for sending pure html
to client without any react hooks.
 unmountComponentAtNode() method will serve opposite of render() method to
unmount the rendered component from DOM.
Renders <DemoApp/> in the
div ‘reactDemoApp’ present
in the html.
React at client
side (SEO)
Get hands dirty
JEST
• Jest is BDD unit testing framework built over Jasmine for testing react and
flux applications.
• Automatically mocks all the require modules.
• Why JEST not Jasmine, directly copied from JEST site (refer jest site for
detailed tutorial):
 Jest provides you with multiple layers on top of Jasmine:
 Automatically finds tests to execute in your repo
 Automatically mocks dependencies for you when running your tests
 Allows you to test asynchronous code synchronously
 Runs your tests with a fake DOM implementation (via jsdom) so that your tests can
run on the command line
 Runs tests in parallel processes so that they finish sooner
•
JEST - example
Get hands dirty
React Routing (react-router)
• React router (react-router) is useful for implementing routing in SPA
applications at client side.
• Ideal for using it in SPA application for handling different routes.
• It has dependency on history api for managing URLs in the browser history.
• react-router exports react components for creating routing on client site.
• React-router api provides following components
 Router - route level node for nesting routes.
 Route - individual route
 IndexRoute – default route if there is no root level route set
 Redirect – to handle redirects in the router
• Refer this link for full api:
 https://github.com/rackt/react-router/
react-router- usage
• import {Router, Route, IndexRoute,Redirect} from 'react-router'
FLUX
Unidirectional Data flow Architecture
What is Flux?
• Flux is an application architecture pattern from Facebook for building client
side web applications using unidirectional data flow.
• Data in flux application flows in single direction
Source:https://facebook.github.io/flux
Flux Architecture Explained
• Dispatcher
 Responsible for dispatching actions to all the callbacks registered by stores themselves
with dispatcher.
 Doesn’t have any logic on its own.
• Store
 Stores register callbacks with dispatcher with action type.
 Use waitFor() to maintain dependencies between stores in an event StoreB needs to be
invoked before StoreA.
 Connect with server to get and update application state.
• Action / Action Creators
 Responsible for invoking dispatcher with appropriate event type.
 Generate actions in response to event listeners.
• React View Components
 Listening to change events, retrieve data and send it to all its child components for
rendering changes.
React + Flux life cycle
JEST for Flux
• Jest provides an easy way to test flux applications.
• Detailed API is available at this location.
• https://facebook.github.io/flux/docs/testing-flux-applications.html
JEST Dispatcher Test Example
References - Best for getting deeper understanding
• React JS
 https://facebook.github.io/react/docs/getting-started.html
• React JEST
 https://facebook.github.io/jest/docs/tutorial-react.html
• es2015
 http://people.mozilla.org/~jorendorff/es6-draft.html#sec-constructor
• Flux
 https://facebook.github.io/flux/docs/overview.html
Call to action
• Practice Rect and Flux combination
• Read about React Native.
 https://facebook.github.io/react-native/
Thank You
Hope it helps at least a little.

More Related Content

What's hot (20)

PPTX
Reactjs
Neha Sharma
 
PDF
Introduce Flux & react in practices (KKBOX)
Hsuan Fu Lien
 
PDF
Getting Started with React-Nathan Smith
TandemSeven
 
PDF
Understanding Facebook's React.js
Federico Torre
 
PPTX
Intro to React
Eric Westfall
 
PPTX
20180518 QNAP Seminar - Introduction to React Native
Eric Deng
 
PDF
An Overview of the React Ecosystem
FITC
 
PDF
React – Structure Container Component In Meteor
Designveloper
 
PPT
React js
Jai Santhosh
 
PDF
Workshop React.js
Commit University
 
PPTX
React js for beginners
Alessandro Valenti
 
PPTX
Introduction to React JS
Arnold Asllani
 
PPTX
React - Start learning today
Nitin Tyagi
 
PDF
React-js
Avi Kedar
 
PDF
ReactJS presentation
Thanh Tuong
 
PPTX
React js programming concept
Tariqul islam
 
PPTX
Introduction to react_js
MicroPyramid .
 
PDF
React for Dummies
Mitch Chen
 
PPTX
React js
Alireza Akbari
 
Reactjs
Neha Sharma
 
Introduce Flux & react in practices (KKBOX)
Hsuan Fu Lien
 
Getting Started with React-Nathan Smith
TandemSeven
 
Understanding Facebook's React.js
Federico Torre
 
Intro to React
Eric Westfall
 
20180518 QNAP Seminar - Introduction to React Native
Eric Deng
 
An Overview of the React Ecosystem
FITC
 
React – Structure Container Component In Meteor
Designveloper
 
React js
Jai Santhosh
 
Workshop React.js
Commit University
 
React js for beginners
Alessandro Valenti
 
Introduction to React JS
Arnold Asllani
 
React - Start learning today
Nitin Tyagi
 
React-js
Avi Kedar
 
ReactJS presentation
Thanh Tuong
 
React js programming concept
Tariqul islam
 
Introduction to react_js
MicroPyramid .
 
React for Dummies
Mitch Chen
 
React js
Alireza Akbari
 

Viewers also liked (20)

PPTX
Oprah Winfrey
Utkarsh Haldia
 
PDF
ReactJS | 서버와 클라이어트에서 동시에 사용하는
Taegon Kim
 
PPTX
Elon Musk
Miloš Ivković
 
PPT
Bill Gates, Who is he?
Victor Gabriel Garcia G.
 
PPT
Reverse Engineering
dswanson
 
PDF
Chess
Chuck Vohs
 
PPTX
Product management
mukku jakkaraiah
 
PDF
Product Management
Teaching Excellence
 
PDF
Personal Development
Seta Wicaksana
 
PDF
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
Spiros
 
PDF
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Zach Lendon
 
PPTX
Manchester city
ofrancis
 
PPTX
Datomic
Jordan Leigh
 
PDF
Datomic
Christophe Marchal
 
PPT
Datomic
jperkelens
 
PDF
Backbone.js
daisuke shimizu
 
PPT
Tesco
Vishal Wadekar
 
PPTX
intel core i7
kiran bansod
 
PPTX
Waldorf Education
xMerodi
 
Oprah Winfrey
Utkarsh Haldia
 
ReactJS | 서버와 클라이어트에서 동시에 사용하는
Taegon Kim
 
Elon Musk
Miloš Ivković
 
Bill Gates, Who is he?
Victor Gabriel Garcia G.
 
Reverse Engineering
dswanson
 
Chess
Chuck Vohs
 
Product management
mukku jakkaraiah
 
Product Management
Teaching Excellence
 
Personal Development
Seta Wicaksana
 
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
Spiros
 
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Zach Lendon
 
Manchester city
ofrancis
 
Datomic
Jordan Leigh
 
Datomic
jperkelens
 
Backbone.js
daisuke shimizu
 
intel core i7
kiran bansod
 
Waldorf Education
xMerodi
 
Ad

Similar to React and Flux life cycle with JSX, React Router and Jest Unit Testing (20)

PPTX
React, Flux and more (p1)
tuanpa206
 
PDF
React js
Rajesh Kolla
 
PPTX
React Workshop: Core concepts of react
Imran Sayed
 
PPTX
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
PPTX
React workshop
Imran Sayed
 
PPTX
ReactJs
Sahana Banerjee
 
PPTX
Dyanaimcs of business and economics unit 2
jpm071712
 
PPTX
Getting started with react &amp; redux
Girish Talekar
 
PDF
Welcome to React & Flux !
Ritesh Kumar
 
PPTX
ReactJS
Ram Murat Sharma
 
PPTX
unit 2 React js.pptxdgdgdgdgdgdgdgdgdsgdgdg
zmulani8
 
PPTX
class based component.pptx
saikatsamanta49
 
PPTX
reactJS
Syam Santhosh
 
PPTX
ReactJS (1)
George Tony
 
PPTX
React & Redux for noobs
[T]echdencias
 
PPTX
Why React's Awesome!
nomanalikk
 
PDF
REACTJS.pdf
ArthyR3
 
PPTX
ReactJS Code Impact
Raymond McDermott
 
PPTX
React for JavaScipt Introduction and functions
MaithiliGogteParanja
 
PPTX
Presentation on "An Introduction to ReactJS"
Flipkart
 
React, Flux and more (p1)
tuanpa206
 
React js
Rajesh Kolla
 
React Workshop: Core concepts of react
Imran Sayed
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Karmanjay Verma
 
React workshop
Imran Sayed
 
Dyanaimcs of business and economics unit 2
jpm071712
 
Getting started with react &amp; redux
Girish Talekar
 
Welcome to React & Flux !
Ritesh Kumar
 
unit 2 React js.pptxdgdgdgdgdgdgdgdgdsgdgdg
zmulani8
 
class based component.pptx
saikatsamanta49
 
reactJS
Syam Santhosh
 
ReactJS (1)
George Tony
 
React & Redux for noobs
[T]echdencias
 
Why React's Awesome!
nomanalikk
 
REACTJS.pdf
ArthyR3
 
ReactJS Code Impact
Raymond McDermott
 
React for JavaScipt Introduction and functions
MaithiliGogteParanja
 
Presentation on "An Introduction to ReactJS"
Flipkart
 
Ad

Recently uploaded (20)

PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PPTX
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
DOCX
Import Data Form Excel to Tally Services
Tally xperts
 
PPTX
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
PDF
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PDF
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
PPTX
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
PDF
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
PDF
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
PPTX
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
PDF
Executive Business Intelligence Dashboards
vandeslie24
 
PPTX
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PPTX
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
PPTX
Engineering the Java Web Application (MVC)
abhishekoza1981
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Revolutionizing Code Modernization with AI
KrzysztofKkol1
 
Import Data Form Excel to Tally Services
Tally xperts
 
How Apagen Empowered an EPC Company with Engineering ERP Software
SatishKumar2651
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
GetOnCRM Speeds Up Agentforce 3 Deployment for Enterprise AI Wins.pdf
GetOnCRM Solutions
 
Odoo CRM vs Zoho CRM: Honest Comparison 2025
Odiware Technologies Private Limited
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
Build It, Buy It, or Already Got It? Make Smarter Martech Decisions
bbedford2
 
The Role of a PHP Development Company in Modern Web Development
SEO Company for School in Delhi NCR
 
Streamline Contractor Lifecycle- TECH EHS Solution
TECH EHS Solution
 
Linux Certificate of Completion - LabEx Certificate
VICTOR MAESTRE RAMIREZ
 
Agentic Automation Journey Session 1/5: Context Grounding and Autopilot for E...
klpathrudu
 
Executive Business Intelligence Dashboards
vandeslie24
 
MailsDaddy Outlook OST to PST converter.pptx
abhishekdutt366
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Comprehensive Guide: Shoviv Exchange to Office 365 Migration Tool 2025
Shoviv Software
 
Engineering the Java Web Application (MVC)
abhishekoza1981
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 

React and Flux life cycle with JSX, React Router and Jest Unit Testing

  • 1. ReactJS + Flux + JSX + Jest Eswara K Palakollu@Sapient Learn Isomorphic React and Flux Life cycle in detail.
  • 3. What is React? • Reactjs is a java script library for building composable, maintainable and testable user interfaces. • React covers just view ‘V’ in MVC pattern.
  • 4. How does React work? React abstracts application DOM and maintains Virtual DOM in memory for handling in-page interactions and updates from server. React compares previous state of Virtual DOM with new state of Virtual DOM and updates physical DOM with the changed elements. Physical DOM always reflect up to date application state and react updates virtual DOM whenever application state changes and which internally updates physical DOM. React Virtual DOM Physical DOM Application Events Events Only changed elements
  • 5. Why React? • Fast • Unidirectional data flow from parent components to child components. • Isomorphic • Easy to debug & testable • SPA friendly. • Can co-exist with other frameworks and easy to try it out. • Use JSX with familiar HTML like syntax for writing react applications.
  • 7. React at client side (Non-SEO / SPA)
  • 9. JSX • JSX is a ECMASCRIPT syntactic extension similar to HTML and XML. • JSX helps to write secure java script with familiar HTML like syntax. • JSX transpilers help to compile JSX syntactic code into pure java script for execution on browsers. • React JSX transpiler can be used to compile react JSX code into pure java script for execution. • <ProductImage href=“image.jpeg”></ ProductImage>
  • 10. JSX – Syntax • Use Upper case for custom tags <ProductImage><image href=“./image.jpeg”/> </ProductImage> • Use lower case for html tags <image href=“./image.jpeg” /> • Self Closing - <ProductImage href=“./image.jpeg” /> • Child elements - <Product><ProductImage href=“./image.jpeg” /> </Product> • Pass properties - <ProductImage href=“./image.jpeg” /> • Spread attributes <ProductImage {…this.props} /> • Attribute expression <ProductImage href={this.props.href} />
  • 13. Tools and packages • Using ECMA6 compatible REACT API and differences to ECMA5 are called out later. • react, react-addons-test-utils • react-dom, react-dom/server • react-router • flux • babel frameworks • jest – unit testing • webpack
  • 14. React APIs • React.Component API covers component life cycle methods discussed in the coming sections. • ReactDOM – This package provides DOM specific methods such as rendering DOM at client side and server side for SEO benefits.  render() method will be the primary and mandatory method used in this API for rendering components on client side.  renderToString() [react-dom/server] method will be useful to render the component on server side and send HTML to client side for client side binding and event listeners.  findDOMNode() method is useful for reading DOM elements. Mostly refs and event listeners will cover most of the needs.  renderToStaticMarkup() [react-dom/server] method is useful for sending pure html to client without any react hooks.  unmountComponentAtNode() method will serve opposite of render() method to unmount the rendered component from DOM.
  • 16. React Component life cycle explained • getDefaultProps()  This method is called only once and shared between instances of react component for better performance.  Don’t access or update component’s state in this method as this method is called once and shared between instances. • getInitialState()  This method is called every time component is initialized for the first time. In ES6, initial state has to be set in constructor() method as this method is not available.  Set component’s initial state for rendering.  Invoke ajax if data to be retrieved from server on page load. • Mounting: componentWillMount()  This method is called just before initial rendering.  Invoke third party or server call and update components state if necessary.  Updating state will not re-render the component.  Don’t attempt to read physical DOM in this method as component is not yet mounted.
  • 17. React Component life cycle explained • Mounting: componentDidMount()  This method is called just after initial rendering.  Integrate with third party or AJAX calls to server or analytics etc.  Access refs and DOM elements in this method. • Updating: componentWillReceiveProps(nextProps)  Updating component state / props will trigger re-rendering of View.  Updating component state / pros is allowed here.  Updating props from parent can trigger re-rendering of updated child component. • Updating: shouldComponentUpdate(nextProps,nextState)  Return false if rendering of changed state / props is not needed.  By default this method returns true always unless there is a performance reason to return try by comparing previosProps and nextProps  If it returns true componentWillUpdate() and componentDidUpdate() will be called otherwise not called.
  • 18. React Component life cycle explained • Updating: componentWillUpdate(nextProps, nextState)  This method is invoked before rendering when new props or state being received.  Updating state is not allowed in this method. Use componentWillReceiveProps() for updating state. • Updating: componentDidUpdate(prevProps, prevState)  This method is invoked right after component nextProps rendered successfully.  DOM can be accessed in this method.  Third party calls or ajax server calls can be invoked in this method.  Application state / props can be accessed and updated in this method.
  • 19. Unidirectional data flow in React • In react, data flows in one direction from parent to child components using props. • React renders data using component state and the properties sent by parent react component to it. • Component state is maintained by this.state variable and initialised in constructor() aka getIntitialState() in ES5 version. • Properties are usually passed to the component by its parent and this.props will hold all the properties passed by parent. • getDefaultProperties() will be used to initialise the properties and it is invoked only once and shared between instances.
  • 22. Application state • React maintains application state at component level and sends required state attributes to child components via props. • Every time application state changes the changed state is passed to child components to update the views again. • this.state – holds the component state received from server or set by component. • this.props – holds the properties sent by its parent and any callbacks needed to call for updating state in parent that will trigger updated props to this component for updating view again.
  • 23. this.state = {title: ‘I am the initial state’}; • State (this.state) in react refers to component state that will be rendered in View by ReactDOM. • State can be changed by calling this.setState(). React rerenders the component when the state is updated.  this.setState({title: ‘I am the updated state’});  this.setState({title: ‘I am the updated state with callback’,function(){}); • State is private to the component unlike this.props and it can be managed by using react life cycle methods. • While mounting use componentWillMount() method to update state before initial rendering. • While updating the state after initial rendering, use componentWillReceiveProps() before re-rendering or componentDidUpdate() for accessing and updating DOM after rendering based on user or server interaction. • Never assign state to this.state directly instead use this.setState() as updating this.state doesn’t invoke react life cycle correctly.
  • 24. this.props • React props are owned and maintained by parent component. • Parent component sends state to child react components as properties for rendering. • Child tags or html content between opening and closing tags can be accessed using this.props.children. • <ProductImage href=“image.jpeg”> <img src=“image.jpeg”></img> </ProductImage> • this.props.children will give <img src=“image.jpeg”></img> tag. • When this.props are updated, parent broadcasts the change to all its child tags that will invoke componentWillReceiveProps() life cycle method.
  • 25. rest and spread props {a,b,…rest} • Take advantage of ECMA6 arrays destructuring to use rest or spread the properties sent by parent. • let {href , title} = this.props; //spread the required attributes from props • let {href , title, …more} = this.props; //…more holds the rest of the attributes apart from spread attributes href and title.
  • 26. render(){return <h1>hello</h1>)} • render() is the must have function and only mandatory method in every react component. • render must return HTML content or another react child component for rendering. • Render can only render one element for now due to syntactic issues with java script. If multiple elements need to be rendered, surround all the elements with a div or any other element as per the need. render(){ return { <div> <h1>Product Description</h1> <p>print product description here.</p> <ProductMoreDetails id={this.props.product.id} /> </div> } }
  • 28. refs • React provide refs (references) to access DOM after component is displayed. • Avoid using refs as react manages keep component displayed correctly at all times and there shouldn’t be any need to manipulate DOM manually. • Usually accessing DOM may not be required given that react manages updating the DOM when props are propagated from parent or state changes. • In some cases other parts of the bigger application may need to reference DOM to further action. • this.refs. render(){ return { <div> <h1>Product Description</h1> <p ref=“productDescription”>print product description here.</p> </div> } }
  • 29. key attribute • Key attribute optimizes rendering of ordered or unordered list of elements on the page. • If a dropdown has 20 elements and one of the element changed. React will compare the difference using Virtual DOM which eventually end of updating all the items in the dropdown. • Key attribite will help react to identify the changes correctly and update only the changed elements instead of re-rendering unchanged elements. • <ul> • <li key=“sku1”>SKU1</li> • <li key=“sku2”>SKU2</li> • <li key=“sku3”>SKU3</li> • <li key=“sku4”>SKU4</li> • </ul> • React removes “sku1” and inserts “sku5” without touching other elements in the list. <ul> <li key=“sku5”>SKU5</li> <li key=“sku2”>SKU2</li> <li key=“sku3”>SKU3</li> <li key=“sku4”>SKU4</li> </ul>
  • 30. Other attributes • forceUpdate() – It forced react to render without calling shouldComponentUpdate() method. • propTypes() – It allows to type check input prop types before getDefaultProps() is called. For performance reasons this method should only be checked in development environment.
  • 31. ECMA5 vs ECMA6 • React latest 0.14.x supports ECMA6 and few life cycle methods have deprecated from API. I have omitted the api methods that may be removed completely from ECMA6 version. • ECMA5 ES2015(aka ECMA6) React.createClass() used for creating react component classes. var App = React.createClass({ }); Extend React.Component class to create custom components. class App extends React.Component{} Deprecated methods to stay way from using: replaceState() isMounted() getDOMNode() isMounted() setProps() replaceProps()
  • 32. React SEO – Server side rendering • Isomorphic react provides SEO support for compiling HTML at server side and bid the non-seo components at client side. • ReactDOM API provides functionality for executing react component on server side.
  • 33. React DOM API • ReactDOM – This package provides DOM specific methods such as rendering DOM at client side and server side for SEO benefits.  render() method will be the primary method used in this API for rendering components on client side.  renderToString() [react-dom/server] method will be useful to render the component on server side and send HTML to client side for client side binding and event listeners.  findDOMNode() method is useful for reading DOM elements. Mostly refs and event listeners will cover most of the needs.  renderToStaticMarkup() [react-dom/server] method is useful for sending pure html to client without any react hooks.  unmountComponentAtNode() method will serve opposite of render() method to unmount the rendered component from DOM. Renders <DemoApp/> in the div ‘reactDemoApp’ present in the html.
  • 36. JEST • Jest is BDD unit testing framework built over Jasmine for testing react and flux applications. • Automatically mocks all the require modules. • Why JEST not Jasmine, directly copied from JEST site (refer jest site for detailed tutorial):  Jest provides you with multiple layers on top of Jasmine:  Automatically finds tests to execute in your repo  Automatically mocks dependencies for you when running your tests  Allows you to test asynchronous code synchronously  Runs your tests with a fake DOM implementation (via jsdom) so that your tests can run on the command line  Runs tests in parallel processes so that they finish sooner •
  • 39. React Routing (react-router) • React router (react-router) is useful for implementing routing in SPA applications at client side. • Ideal for using it in SPA application for handling different routes. • It has dependency on history api for managing URLs in the browser history. • react-router exports react components for creating routing on client site. • React-router api provides following components  Router - route level node for nesting routes.  Route - individual route  IndexRoute – default route if there is no root level route set  Redirect – to handle redirects in the router • Refer this link for full api:  https://github.com/rackt/react-router/
  • 40. react-router- usage • import {Router, Route, IndexRoute,Redirect} from 'react-router'
  • 42. What is Flux? • Flux is an application architecture pattern from Facebook for building client side web applications using unidirectional data flow. • Data in flux application flows in single direction Source:https://facebook.github.io/flux
  • 43. Flux Architecture Explained • Dispatcher  Responsible for dispatching actions to all the callbacks registered by stores themselves with dispatcher.  Doesn’t have any logic on its own. • Store  Stores register callbacks with dispatcher with action type.  Use waitFor() to maintain dependencies between stores in an event StoreB needs to be invoked before StoreA.  Connect with server to get and update application state. • Action / Action Creators  Responsible for invoking dispatcher with appropriate event type.  Generate actions in response to event listeners. • React View Components  Listening to change events, retrieve data and send it to all its child components for rendering changes.
  • 44. React + Flux life cycle
  • 45. JEST for Flux • Jest provides an easy way to test flux applications. • Detailed API is available at this location. • https://facebook.github.io/flux/docs/testing-flux-applications.html
  • 47. References - Best for getting deeper understanding • React JS  https://facebook.github.io/react/docs/getting-started.html • React JEST  https://facebook.github.io/jest/docs/tutorial-react.html • es2015  http://people.mozilla.org/~jorendorff/es6-draft.html#sec-constructor • Flux  https://facebook.github.io/flux/docs/overview.html
  • 48. Call to action • Practice Rect and Flux combination • Read about React Native.  https://facebook.github.io/react-native/
  • 49. Thank You Hope it helps at least a little.

Editor's Notes

  • #38: Walkthrough this example