Skip to content

Instantly share code, notes, and snippets.

@SanthoshVijayabaskar
Last active December 14, 2015 12:55
Show Gist options
  • Save SanthoshVijayabaskar/9cc741812462ee59233a to your computer and use it in GitHub Desktop.
Save SanthoshVijayabaskar/9cc741812462ee59233a to your computer and use it in GitHub Desktop.
Understanding ReactJS

Introduction to ReactJS

Javascript library for developing user interfaces.

Read more on React @ http://facebook.github.io/react

Why React?

1. Fast
2. Reusable and Composable components
3. Pluggable
2. Virtual DOM (Performance)
3. Isomorphic Rendering (Rendered both in client and Server)
4. Simple (Usually 'V'/'CV' in 'MVC')
4. Uni-Directional Flow -Source of data change is easy to track (In two way data binding, its hard to predict Interaction in complex application)
5. Community & Support (Battle Proven)
--> Used by: Facebook, Instagram, Adobe, Paypal and many more sites in Production

Advantage

  1. Speed (Renders 60 fps)
    React Render Process < 16ms
  2. Declarative
    Easier to reason about
    Easier to prevent bugs
  3. Composable
    Components have , Inputs as Properties and Output as callbacks

Concepts: Overview

What is Components?

Components are building blocks of React

  • Each components maps to DOM Node which may have decendant nodes
  • Components are composable
  • createClass is used to create React Components which takes atleast one parameter "render" function
  • Render method renders the components into the DOM
  • Props provides the immutable data for a components
  • State Provides the mutable data for a components
  • propTypes allows basic validation on props
  • Mixins allow reuse between components without duplicating code
  • props send data to a components and callbacks sending data from one component to another

Top-level namespace is React

Props and State

Data for any react application is held in two places,

  • Props - Looks like HTML Attribute, but Immutable (Example: this.props.username)
  • State - Hold mutable state (Example: this.state.username)

FAQ: Why Props are Immutable?

AS they are passed by parent component to the child, the props are owned by parent and hence are immutable.

Component Lifecycle Methods

  • componentWillMount
    When: Before Initial Render, both Client and Server
    Why: Good Spot to set Initial State
  • componentDidMount
    When: After render
    Why: Access DOM, Integrate with Framework, set Timers, AJAX Requests
  • componentWillReceiveProps
    When: Called When receiving new Props, not called on initial render
    Why: Set State before Render
  • shouldComponentUpdate
    When: Before render when new props or state are being received. Not called on Initial render
    Why: Performance. Return false to void un-necessary re-renders
  • componentWillUpdate
    When: Immediately before rendering when new props and state are being received. Not called on Inital render
    Why: Prepare for an Update
  • componentDidUpdate
    When: After component's updates are flushed to the DOM. Not called on the initial render
    Why: Work with the DOM after Update
  • componentWillUnmount
    When: Immediately before the component is removed from the DOM
    Why: Cleanup

Keys for Dynamic Children

Add a key to dynamic child elements

tr key={author.id}

Controller View

The Top Level Component in React is usually called a Controller View which passes the props on to the child component and interacts with stores.

Mixins

  • For Cross cutting concerns
  • Share Code between multiple components
  • Usage: mixins:[Router.Navigation,Router.State]

Navigation Mixins

![mixins_navigation](https://cloud.githubusercontent.com/assets/1716894/10757091/974b6e5e-7cce-11e5-8e45-f8301ebe4d0e.png)

Concepts: Demos

Basic

Basic React JS Hello World @ https://jsfiddle.net/reactjs/69z2wepo/

Composing

Composing React Component Demo @ http://jsfiddle.net/kb3gN/364/
Blog Post Example for Composing Components @ http://jsfiddle.net/kb3gN/427/
Blog Post Example with Map Function on Comments @ http://jsfiddle.net/kb3gN/428/

getInitialState

* getInitialState - allows a component to populate its initial state
* setState is a function used to update the state of the component
* setState mergers the New state with the old state

setstate

getInitialState Example @ http://jsfiddle.net/kb3gN/366/
getInitialState Example with setState @ http://jsfiddle.net/kb3gN/367/
getInitialState Demo with Stateless Component @ http://jsfiddle.net/kb3gN/368/

getDefaultProps

* getDefaultProps - It provides property values to use if they are not explicitly supplied
* The values declared within this will be used by the component if the parent component has not declared the props.

getDefaultProps Demo @ http://jsfiddle.net/kb3gN/371/

Validating Proprties

* Validate Props with PropTypes
* Supports validation of existence, data types or a custom condition
* PropTypes only works in development mode, as minified version of React is used in Production * NOTE: Every propType that isn't required should have a corresponding field in getDefaultProps

proptypes_1

proptypes

Demo @ http://jsfiddle.net/kb3gN/442/

Mixins

* A mixin is a partial definition of a React component that can be added to multiple other components. * Mixins allows common code to be merged into many components

Demo of Common Functions [without Mixins] @ http://jsfiddle.net/kb3gN/376/
Common Functions with Mixins @ http://jsfiddle.net/kb3gN/375/

JSX - Deprecated

* JSX is the default syntax and pre-processor of React * JSX is Optional * Supports xml-like syntax inline in Javascript * Each element is transformed into a JS function call * Arrtibutes : The Values of JSX attributes can be Strings or Javascript Expression * Transformations can be
--> Just-In-Time
--> Precompiled by react tools

Just-in-Time JSX

* Disadvantage: Script includes the JSX is not a JavaSript, It cannot be minified, debugged in browser, processed through linter or formatted using JS Syntax Highlighter. * Significant Performance Penalty

Precompiler JSX

* Use Some build tools and Pre compile the JSX for Improved Performance.

Child Expression for JSX

Demo @ http://jsfiddle.net/kb3gN/448/
Another Demo with this.props.children concept @ http://jsfiddle.net/kb3gN/452/

HTML Attributes

* HTL attributes cannot use Javascript Reserved Key word.

label--> htmlFor="name" className="big"
style={{...}} (or) style={s} and define var s={...}

Unescaping Content

Escaped Content means a string representation of HTML that is not interpreted as HTML.
  • React escapes everything by default
  • Bypass using dangerouslySetInnerHTML
  • Excepts an Object with an __html property
    dangerouslysetInnerHTML={{__html="Foo"}}
    Demo @ http://jsfiddle.net/kb3gN/461/

Events

  • React has its own Event Abstraction
    --> Normalizes Event behaviour (make events work the same in all browsers)
    --> Uniform event system for DOM Events and Component Events
  • Synthetic Event
    --> Original Event Object is available via the nativeEvent Property

DOM Events

Component Events

Forms

Controlled Component

* Controlled components are Form components with values or checked attribute. * They always maintain the synchronization between component markup and with the props and states passed * Preserve React's rendering semantics * Change value of Controlled Components : change the state {this.setState({})}
Demo @ http://jsfiddle.net/kb3gN/514/ - Using Props
Demo @ http://jsfiddle.net/kb3gN/513/ - Using SetState

Uncontrolled Components

  • UnControlled Components let the values change independently with the owning component props and states.
  • Form components rendered without a value or checked prop
    Demo @ http://jsfiddle.net/kb3gN/512/ - Uncontrolled components

Refs

  • Provide a way to reference owned component
  • Usage:
    --> Add a ref attribute to the react DOM Component to name the component instance
    --> Access the element via this.refs.element_name
  • We can access this.refs only after the component is rendered, which means we cannot access this.refs within ComponentsWillMount
    Demo @ http://jsfiddle.net/kb3gN/515/ - Using Refs
    Demo @ http://jsfiddle.net/kb3gN/516/ - Usiing Refs

getDOMNode

  • React Components are often mapped to DOM Node. The getDOMNode() method helps to get the inderlying DOM Node from React Component Instance.
    Demo @ http://jsfiddle.net/kb3gN/595/

Routing

  • Client-side routing with HTML5 pushState API:
    url0
    --> pushState allows Javascript to update the browser URL
    --> Uses proper URL and better Bookmarking Support
    Disadvantage:
    --> Require a browser that supports pushState
    --> Require server-side support
  • Client-side routing with Hash Fragments
    url1
    --> Works because the hash fragment is never sent to the server
    --> Works in all browser
  • When SEO is not needed, we can go for Client-side routing with Hash Fragments

Understanding React Router

  • React-Router is an Routing library used when there are multiple client rendered pages with deep linking
  • Nested Views map to nested Routes
  • Declarative
  • Used at Facebook and Supported by facebook
  • Inspired by Ember

Route Configuration

* Route - Declaratively map a route * DefaultRoute - For URL of '/' (like Index.html) * NoteFoundRoute - Client-side 404 * Redirect - Redirect to another route

Params and QueryString

![params_routes](https://cloud.githubusercontent.com/assets/1716894/10752705/a8051d84-7cb1-11e5-81b5-d34767405c4a.png)

Links

* It no longer does a full Post back for Page Routes * No hardcording multiple reference to a route, we can handle a centrailzed route URL which is easier to maintain and can be referenced throughout the application.
![link](https://cloud.githubusercontent.com/assets/1716894/10752770/60df766a-7cb2-11e5-94f6-863dd803be8b.png)

DefaultRoute and NotFoundRoute

The above Routes are defined in Routes File to load the default page for the former and 404 Page to the later Route.

Redirects

Need to change a URL? We can use Redirect

redirect

Handling Transition

  • willTransitionTo - Determine if Page should transition to (Example: We can check if the User is Authenticated before transitioning to specific page)
  • willTransitionFrom - Runs checks before user navigates away (Example: Check if the form has un-saved data and prompt the user to save the data)

transition

Clean URL's

Hash vs History URL's

![hashlocation](https://cloud.githubusercontent.com/assets/1716894/10756931/39f49088-7ccd-11e5-864f-bba3f879c911.png)

Handling Forms in React

Following are some of the concepts need to be learnt to handle Forms in React


* Validation * Redirects * Reusable Inputs * User Notification * Saving and Populating on Load

Recommended Project Tech Stack

techstack

#CommonJS Pattern

commonjs_pattern

#ES5 vs ES2015 (ES6) vs

Rethinking the established Best Practices

pic1

Controvertial Ideas by React to rethink frontend Engineering,

  • HTML should be an projection of an App State, not the Source of truth
    --> In React, your app is a function of props and State, We dont Store anything in the DOM - DOM is just an implementation detail
  • Javascript and HTML belong in the same file
  • Uni-Directional data Flow .No two way data binding
  • Inline styles can be good and increase code maintainability.

Comparison to other Libraries

  1. React and Knockout
    --> Both Provide
    * Rendering a model to the DOM
    * Events
  2. React and AngularJS or Ember
    --> Angular and ember are larger and more generalized
  3. React and Backbone
    --> It is common to use React as an alternative view component for Backbone

Why not?

![why-not](https://cloud.githubusercontent.com/assets/1716894/10729614/96246468-7c10-11e5-9bf9-66a058c5ab32.png)

Rendering in React Vs Other Libraries/Framework

![update_react_render](https://cloud.githubusercontent.com/assets/1716894/10730764/e2d7b790-7c17-11e5-91d8-eb5c01aa71fd.png)

Rendering in React Vs Backbone

monkeys
Read more on React Vs Backbone @ http://joelburget.com/backbone-to-react/

Architecture

arch

#Performance in React

  • Include "shouldComponentUpdate" method in Components - Not to Change DOM even for certain Data Change
  • PureRenderMixin + immutability data structure (can do reference comparison)
  • Synthetic Events (In React, attach event handlers at the highest level at effeciency)
  • Virtual DOM, Isomorphic Support
  • React Native

API Documentation

getDOMNode()

* OLD Usage: this.refs.inp.getDOMNode().value = "Santhosh"
* NEW Usage: React.FindDOMNode(this.refs.inp) = "Santhosh"

What Gulp can do for you?

  1. Compile React JSX
  2. Lint JSX and JS via ESLint (Helps adheres to coding standards and alert us when we have issues in our code)
  3. Bundle JS and CSS Files
  4. Migrate the built app to the dist folder
  5. Run a dev webserver
  6. Open the browser at your dev URL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment