SlideShare a Scribd company logo
1 of 49
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

Introduce Flux & react in practices (KKBOX)
Introduce Flux & react in practices (KKBOX)Introduce Flux & react in practices (KKBOX)
Introduce Flux & react in practices (KKBOX)Hsuan Fu Lien
 
Getting Started with React-Nathan Smith
Getting Started with React-Nathan SmithGetting Started with React-Nathan Smith
Getting Started with React-Nathan SmithTandemSeven
 
Understanding Facebook's React.js
Understanding Facebook's React.jsUnderstanding Facebook's React.js
Understanding Facebook's React.jsFederico Torre
 
20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React NativeEric Deng
 
An Overview of the React Ecosystem
An Overview of the React EcosystemAn Overview of the React Ecosystem
An Overview of the React EcosystemFITC
 
React – Structure Container Component In Meteor
 React – Structure Container Component In Meteor React – Structure Container Component In Meteor
React – Structure Container Component In MeteorDesignveloper
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JSArno Lordkronos
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today Nitin Tyagi
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentationThanh Tuong
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_jsMicroPyramid .
 
React for Dummies
React for DummiesReact for Dummies
React for DummiesMitch Chen
 

What's hot (20)

Reactjs
Reactjs Reactjs
Reactjs
 
Introduce Flux & react in practices (KKBOX)
Introduce Flux & react in practices (KKBOX)Introduce Flux & react in practices (KKBOX)
Introduce Flux & react in practices (KKBOX)
 
Getting Started with React-Nathan Smith
Getting Started with React-Nathan SmithGetting Started with React-Nathan Smith
Getting Started with React-Nathan Smith
 
Understanding Facebook's React.js
Understanding Facebook's React.jsUnderstanding Facebook's React.js
Understanding Facebook's React.js
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native
 
An Overview of the React Ecosystem
An Overview of the React EcosystemAn Overview of the React Ecosystem
An Overview of the React Ecosystem
 
React – Structure Container Component In Meteor
 React – Structure Container Component In Meteor React – Structure Container Component In Meteor
React – Structure Container Component In Meteor
 
Learn react-js
Learn react-jsLearn react-js
Learn react-js
 
React js
React jsReact js
React js
 
Workshop React.js
Workshop React.jsWorkshop React.js
Workshop React.js
 
React js for beginners
React js for beginnersReact js for beginners
React js for beginners
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
React - Start learning today
React - Start learning today React - Start learning today
React - Start learning today
 
React-js
React-jsReact-js
React-js
 
ReactJS presentation
ReactJS presentationReactJS presentation
ReactJS presentation
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
Introduction to react_js
Introduction to react_jsIntroduction to react_js
Introduction to react_js
 
React for Dummies
React for DummiesReact for Dummies
React for Dummies
 
React js
React jsReact js
React js
 

Viewers also liked (20)

Oprah Winfrey
Oprah WinfreyOprah Winfrey
Oprah Winfrey
 
ReactJS | 서버와 클라이어트에서 동시에 사용하는
ReactJS | 서버와 클라이어트에서 동시에 사용하는ReactJS | 서버와 클라이어트에서 동시에 사용하는
ReactJS | 서버와 클라이어트에서 동시에 사용하는
 
Elon Musk
Elon MuskElon Musk
Elon Musk
 
Bill Gates, Who is he?
Bill Gates, Who is he?Bill Gates, Who is he?
Bill Gates, Who is he?
 
Reverse Engineering
Reverse EngineeringReverse Engineering
Reverse Engineering
 
Chess
ChessChess
Chess
 
Product management
Product managementProduct management
Product management
 
Product Management
Product ManagementProduct Management
Product Management
 
Personal Development
Personal DevelopmentPersonal Development
Personal Development
 
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)elm-d3 @ NYC D3.js Meetup (30 June, 2014)
elm-d3 @ NYC D3.js Meetup (30 June, 2014)
 
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
Reconciling ReactJS as a View Layer Replacement (MidwestJS 2014)
 
Growth Hacking
Growth Hacking Growth Hacking
Growth Hacking
 
Manchester city
Manchester cityManchester city
Manchester city
 
Datomic
DatomicDatomic
Datomic
 
Datomic
DatomicDatomic
Datomic
 
Datomic
DatomicDatomic
Datomic
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Tesco
TescoTesco
Tesco
 
intel core i7
intel core i7intel core i7
intel core i7
 
Waldorf Education
Waldorf EducationWaldorf Education
Waldorf Education
 

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

React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
React, Flux and more (p1)
React, Flux and more (p1)React, Flux and more (p1)
React, Flux and more (p1)tuanpa206
 
Getting started with react &amp; redux
Getting started with react &amp; reduxGetting started with react &amp; redux
Getting started with react &amp; reduxGirish Talekar
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
Spfx with react redux
Spfx with react reduxSpfx with react redux
Spfx with react reduxRajesh Kumar
 
class based component.pptx
class based component.pptxclass based component.pptx
class based component.pptxsaikatsamanta49
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfStephieJohn
 
How can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state pptHow can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state pptBOSC Tech Labs
 
Optimizing your use of react life cycles by shedrack akintayo
Optimizing your use of react life cycles by shedrack akintayoOptimizing your use of react life cycles by shedrack akintayo
Optimizing your use of react life cycles by shedrack akintayoShedrack Akintayo
 
Introduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsIntroduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsFederico Torre
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxBOSC Tech Labs
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionWorkshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionVisual Engineering
 
How To Utilize Context API With Class And Functional Componen in React.pptx
How To Utilize Context API With Class And Functional Componen in React.pptxHow To Utilize Context API With Class And Functional Componen in React.pptx
How To Utilize Context API With Class And Functional Componen in React.pptxBOSC Tech Labs
 

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

React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
Intro react js
Intro react jsIntro react js
Intro react js
 
React, Flux and more (p1)
React, Flux and more (p1)React, Flux and more (p1)
React, Flux and more (p1)
 
Getting started with react &amp; redux
Getting started with react &amp; reduxGetting started with react &amp; redux
Getting started with react &amp; redux
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
Spfx with react redux
Spfx with react reduxSpfx with react redux
Spfx with react redux
 
class based component.pptx
class based component.pptxclass based component.pptx
class based component.pptx
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
React workshop
React workshopReact workshop
React workshop
 
React Native Firebase
React Native FirebaseReact Native Firebase
React Native Firebase
 
How can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state pptHow can you force react components to rerender without calling the set state ppt
How can you force react components to rerender without calling the set state ppt
 
Optimizing your use of react life cycles by shedrack akintayo
Optimizing your use of react life cycles by shedrack akintayoOptimizing your use of react life cycles by shedrack akintayo
Optimizing your use of react life cycles by shedrack akintayo
 
Introduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic AppsIntroduction to React, Flux, and Isomorphic Apps
Introduction to React, Flux, and Isomorphic Apps
 
reactJS
reactJSreactJS
reactJS
 
React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
Intro to React.js
Intro to React.jsIntro to React.js
Intro to React.js
 
Workshop 19: ReactJS Introduction
Workshop 19: ReactJS IntroductionWorkshop 19: ReactJS Introduction
Workshop 19: ReactJS Introduction
 
How To Utilize Context API With Class And Functional Componen in React.pptx
How To Utilize Context API With Class And Functional Componen in React.pptxHow To Utilize Context API With Class And Functional Componen in React.pptx
How To Utilize Context API With Class And Functional Componen in React.pptx
 
ReactJS
ReactJSReactJS
ReactJS
 

Recently uploaded

JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfMarharyta Nedzelska
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxRTS corp
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITmanoharjgpsolutions
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 

Recently uploaded (20)

JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
A healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdfA healthy diet for your Java application Devoxx France.pdf
A healthy diet for your Java application Devoxx France.pdf
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024VictoriaMetrics Anomaly Detection Updates: Q1 2024
VictoriaMetrics Anomaly Detection Updates: Q1 2024
 
Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptxThe Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
The Role of IoT and Sensor Technology in Cargo Cloud Solutions.pptx
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Best Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh ITBest Angular 17 Classroom & Online training - Naresh IT
Best Angular 17 Classroom & Online training - Naresh IT
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 

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

  1. Walkthrough this example