ReactJS

Learn once, Write anywhere

Created by NTUgEEk

What is React?

react

Javascript library released by Facebook in 2015 for web front-end

  • Component based
  • -> reusable and composable

Installation

See doc
  • CDN(fast but not recommended)
                     
    
    
                     
                  
  • package manager(yarn, npm) with bundler(webpack, browserify) & compiler(babel)
                     
    npm init
    npm install --save react react-dom
                     
                  
  • create-react-app (recommended)
                     
    npm install -g create-react-app
    create-react-app appName
    
    cd appName && npm start
                     
                  


Hello world


              
                 
               
// index.js
ReactDOM.render(
  

WooooooooW

, document.getElementById('root') >
See doc

Component

Similar to OOP conceptually

Create your own HTML tags!

              
import React, { Component } from 'react';

class Hello extends Component {
 render() {
     return (
       

Heeeeeeeeello

) } } export default Hello;
See doc

Props

Similar to data member conceptually(initialized on creation)

              
import React, { Component } from 'react';
class Hello extends Component {
 render() {
     return (
        

Hi, {this.props.text}

) } } export default Hello;
  • Only can be modified from outside.
  • Once modified, the component will be rerendered.

State

Essentially a js object(dictionary)

              
class Clock extends Component {
  constructor(props) {
    super(props);
    this.state = {
       time: 0
    }
  }
  render() {
     setInterval(() => this.setState({time: new Date.getUTCSeconds()}), 1000)
     return (
       

It's {this.state.seconds}

) } }
  • States can only be modified from inside.
  • Like props, the component will be rerendered on state's change.
  • Always use setState to modify state
See doc

Lifecycle

Component's events

  • componentWillMount() : runs before the component output has been rendered
  • componentDidMount() : runs after the component output has been rendered

For more information, refer to the doc above

Practice--lifting states

See doc

Redux

redux

Managing state easily

Doc

What is redux?

Redux is a predictable state container for Javascript app

Concept

react-redux-bubble

Data flow(React-redux)

References

Connecting Redux with React Components

See doc

Data flow

  1. Components use redux's state as part of UI.
  2. User action invoke(onClick, onChange) UI to dispatch action created by actionCreator.
  3. Reducer get notified and return the new state.
  4. The Component is rerendered.

Separating Components

Container Components

  • Handling UI data flow
  • Use connect to connect to redux state
  • Connected will have dispatch props
  • Use mapStateToProps to take redux state to props

Done!!

Practice--TodoList

See doc

There are still more