Why React?

Road to React

by Julia Dizhak

March - October 1,2 2018

moneypark

Many thanks

Agenda

  • The brief history of React
  • Why React?
  • JSX
  • React components
  • props and state
  • virtual DOM and Diff algorithm
  • unidirectional data flow
  • Component lifecycle
  • React synthetic events

a brief history

August 26, 2006, 12 years ago - introduced Jquery by John Resig

2010, 7 years ago - Backbone released

2011-2012 - AngularJS become popular (created by Google)

March 2013; 5 years ago React realised by Jordan Walke

JS frameworks / libraries

  1. Angular2 (AngularJS === Angular1)
  2. ReactJS
  3. VueJS
  4. EmberJS
comparison

Dan Abramov tweet about VueJS

Framework & Library

=> React is a library

React

It's a JS library for building UI created and maintained by Facebook.

React current version is 16.5

celebration anniversary 5 years

Facebook has 50,000 React components

How do you manage large project directories with many components?

Why is React?

Potential problems

React can be used to:

Around it people built whole universe with Redux (Flux implementation).

There’re dozens of libs like: React-boostrap, React material design, React sliders, scrollers, grids, React animations and ...

Next generation of JS

summary pdf

Okay, let's start with React.

Do you wanna see code examples?

Create HTML element by vanila JS

                
                    inside script tag
                    const rootElement = document.getElementById('mountNode');   
                    
                    const element = document.createElement('div');
                    element.textContent = 'Hi JS! Pure JS!';
                    element.className = 'container';
                    rootElement.appendChild(element);
                
            
codepen example

Create HTML element with React's createElement API

                
                    import react.js, react-dom.js
                    inside script tag
                    const mountElement = document.getElementById('mountNode');   
                    const element = React.createElement(
                           'div',  {className: 'container'},'I love React'
                    );
                    ReactDOM.render(element, mountElement);
                
            
codepen example

How to use React.createElement children parameter

                
                    const element = React.createElement(
                           'div',  {className: 'container'},
                              React.createElement('span', {className: 'child'}, 'some text'),
                           ...
                    );
                
            

Replace React createElement method with JSX

                
                    import react.js, react-dom.js, babel!
                    inside script tag
                    const mountElement = document.getElementById('mountNode');   
                    const element = <div className="wrap">I love React</div>
                    ReactDOM.render(element, mountElement);
                
            
codepen example

JSX

JSX can be used

To render HTML tags

                         
                            const element = <div className="wrap"/>
                            ReactDOM.render(element, document.getElementById('mountNode'));
                        
                    

To render React Component

                         
                            const element = <CustomComponent className="wrap"/>
                            ReactDOM.render(element, document.getElementById('mountNode'));
                        
                    

A couple of things about JSX

  1. in HTML, you use class, and in JSX, you use className
  2. Expressions {}.
  3. You don't have to use JSX with React. You can just use plain JS. However, we recommend using JSX because it is a concise and familiar syntax for defining tree structures with attributes.

JSX expressions

JSX expressions

Ternary operator in JSX

                 
                    syntax
                    condition ? expression1 : expression2 
                
            

You can’t use a regular if statement, but a ternary expression is ok.

                 
                    const element = <div className={(4 < 2) ? 'customClassName' : 'errorClassName'}>..</div>
                
            

React.Fragment

JSX elements must be wrapped in an enclosing tag

Or you can use React.Fragment for this purpose

React is all about components

React is designed around the concept of reusable components.

You define small components and you put them together to form bigger components.

All components are reusable, even across different projects.

codepen example

React component

                 
                    function Button(props) {   
                           return (
                                  <button>{props.text}</button>
                               );
                    }
                    const element = (
                        <div className="container">
                           <Button text="click on me" /> 
                           <Button text="I ♥ React" /> 
                        </div> 
                    )
                
            

Everything is/can be a component

React Component

How UI looks like?

  • HTML
  • CSS
  • JS
JSX vs Html

How React looks like?

  • JS + JSX
  • CSS
  • JS
JSX vs Html

React component merges view and logic

React Component React Component

Conditionally render a React Component

codepen example
                 
                    function DisplayMessage(props) {
                        return (
                               <div>
                                  {props.message ? (
                                         <div>{props.message}</div>
                                      ) : (
                                            <div>No Message</div>
                                          )}
                                        </div>
                        );
                    }
                
            

Style inline in React component

                 
                    function Button(props) {   
                        const style = {
                               paddingLeft: '20px',
                               backgroundColor: 'orange'
                        }
                           return (
                                  <button style={style}>{props.text}</button>
                               );
                    }
                
            

Handling data in React

Props and state

Props

Props are external, and not controlled by the component itself.

It’s passed down from components higher up the hierarchy, who also control the data.

                
                    function TextInput(props) {   
                           return (
                                  <input 
                                     type={type}
                                     className={inputClassName}
                                     placeholder={placeholder}
                                     pattern={pattern}
                                     onChange={this.handleChange}
                                      ...
                            />
                               );
                    }
                    Button.propTypes = {
                           text: PropTypes.string
                    }
                
            

Validate custom React component props

                
                    import additional script prop.types.js
                    function Button(props) {   
                           return (
                                  <button>{props.text}</button>
                               );
                    }
                    Button.propTypes = {
                           text: PropTypes.string
                    }
                
            

Types of props

                
                           PropTypes.string 
                           PropTypes.bool
                           PropTypes.number
                           PropTypes.array
                           PropTypes.oneOfType({...})
                           PropTypes.any
                           ...
                
            

PropTypes

                
                    import script prop.types.js
                    function Button(props) {   
                           return (
                                  <button type={props.type}>
                                     {props.text}
                                  </button>
                               );
                    }
                    Button.propTypes = {
                           text: PropTypes.string.isRequired
                    }
                
            

Default props

                
                    import script prop.types.js
                    function Button(props) {   
                           return (
                                  <button type={props.type} />
                               );
                    }
                    Button.defaultProps = {
                           type: 'submit'
                    }
                
            

PropTypes it’s not the same as Typescript or FLow.

PropTypes is a basic type checker which has been patched onto React. It can check only props from Component.

If you want more flexible type checking for your entire project then Flow/TypeScript are appropriate choices.

Rerender a React app

codepen example

Where is the magic?

React is doing the minimal required DOM operations for the render. It’s only will be rerender the necessary part and this is making React app very fast.
virtual dom

Diff algorithm

React diff algorithm is used to compute minimum sets of mutation

Diff Algorithm

State

The second type of data in React is a state.

The state is private data of the component and can be changed from within the component itself.

So if we want the component to be able to change its own data, then we have to use state instead props!

State and props

Difference between state and props

Props

  • are immutable
  • come to the component from parent component/components
  • are initialization data

State

  • is mutable
  • should or can't be accessed from child components

Statefull component

React component — in its simplest form — is a plain-old JS function.

But there is other way to build a component. You can create this component with JS classes syntax.

It’s called Statefull component.

codepen example

Changing the state

to modify the state, only call this.setState()

                
                    constructor(props) {
                           super(props);   
                           this.state = {
                                  value: this.props.value
                               };
                        }
                        handleChange(event) {
                               this.setState({
                                      value: event.target.value
                            });
                        }
                    }        
                
            

Unidirectional Data flow

codepen example

Components hierarchy

  • Lets say we want to develop something like this:
  • First of all let separate it to the components: whole widget, Grid, Grid Record, Grid Action cell, Filter
  • Components hierarchy: Whole widget -> Grid -> Grid Record ->
    Grid Record Action -> Filter
Data flow

Should a Component have state?

state is optional, state increases complexity and reduces predictability.

A Component without state is preferable, avoid having many stateful Components

Component types

React events

Two options: events listeners and React synthetic events

Add listeners to do something in the dom, which is not under react control:

Events ouside React Component

React Synthetic events

Synthetic events: event handler in react elements. It works quite close to pure JavaScript, but with JSX.

Events in React Component

List of available events:

  1. onCopy onCut onPaste
  2. onCompositionEnd onCompositionStart onCompositionUpdate
  3. onKeyDown onKeyPress onKeyUp
  4. onFocus onBlur
  5. onChange onInput onSubmit
  6. onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseOut onMouseOver onMouseUp
  1. onSelect
  2. onTouchCancel onTouchEnd onTouchMove onTouchStart
  3. onScroll
  4. onWheel
  5. onLoad onError
  6. onAnimationStart onAnimationEnd onAnimationIteration
  7. onTransitionEnd
  8. onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata

Use the key prop when rendering a List

Each child in an array or iterator should have a unique key prop.

Key is one helper to React to embrace its full potential and improve performance.

Key attribute should be stable identifier.

codepen example

Component lifecycles

Render method in a React component needs to be a pure function

Whole bunch of methods:

Lifecycles

Lifecycles

Lifecycles

Router

code example

Router path

Resources

Meetups in Zurich

Thank you