install npm install -g create-react-app
create create-react-app APPNAME
start npm start
Concepts
Immutability
React forces immutability.
Strings are immutable by default, when you change them in reality you create a new string and assign it to the same variable name. An immutable variable can never be changed. To update its value, you create a new variable. The same applies to objects and arrays.
Instead of changing an array, to add a new item you create a new array by concatenating the old array, plus the new item.
JSX
1 | import React, { Component } from 'react'; |
Component
A component is just a javascript function which will return JSX to the DOM
There are two ways of creating components in React:
- Functional Components (presentational, stateless, dumb components) (best practice)
The
1 | import React from 'react'; |
- Class-based components (containers, smart, stateful components)
1 | class Cmp extends Component { render() { |
Dynamic Content
1 | // in App.js |
Working with Props
Props are used to pass data in parent and Children components
1 | // in App.js |
Use PropTypes
1 | npm install --save prop-types |
1 | import PropTypes from 'prop-types'; |
State
state can only be used in class extending Components. We use state to store some data of the component itself. The state is used to change the component from within. Usually used to trigger an UI update.
- Only class-based component can define and use
state
1 | class App extends Component { |
props
andstate
are CORE concepts of React. Actually, only changes inprops
andstate
can trigger React to re-render your components and potentially update the DOM in the browser.- The
state
of the component should only be abled to be changed in a few components in the app, referred as containers
A wrong way to setState
1 | this.setState({ |
A better apporach to update state based on the old state
1 | this.setState((prevState, props) => { |
Passing methods between components
1 | render() { |
Two Way Binding
1 |
|