Set-up WebPack Config File
Usefull Webpack Plugins:
Check migration solutions for Webpack 2
-
path Contains several helper functions to help make path manipulation easier.
-
process.env Returns an object containing the user environment.
-
HtmlWebpackPlugin: Simplifies creation of HTML files to serve webpack bundles.
-
autoprefixer: Parse CSS and add vendor prefixes to rules by Can I Use.
-
CaseSensitivePathsPlugin Enforces case sensitive paths in Webpack requires.
-
InterpolateHtmlPlugin Webpack plugin for interpolating custom variables into index.html
(This plugin is supposed to work with HtmlWebpackPlugin) -
WatchMissingNodeModulesPlugin Ensures
npm install <library>
forces a project rebuild -
css-loader CSS loader module for Webpack.
-
style-loader Adds CSS to the DOM by injecting a <style> tag.
-
sass-loader Compiles Sass to CSS.
-
less-loader Compiles Less to CSS.
-
extract-text-webpack-plugin Extract text from bundle into a file.
-
webpack-dev-server Provides a server and live reloading. (Serves from memory)
-
hot-module-replacement Exchanges, adds, or removes modules while an application is running without a page reload.
-
webpack-merge Merge multiple configs and concatenate them.
-
ProvidePlugin Automatically loads modules.
new webpack.ProvidePlugin({ $: 'jquery', /* $('#selector'); */ jQuery: 'jquery', /* jQuery('#selector'); */ _map: ['lodash', 'map'], /* Use map from Lodash */ 'React': 'react', 'ReactDOM': 'react-dom' })
-
rimraf A
rm -rf
util for nodejs
Define Resolves Paths:
const srcDir = path.resolve(__dirname, 'src');
const distDir = path.resolve(__dirname, 'dist');
Separate Dev and Prod ENV Configs Files:
webpack-common.config.js
: Common Configs
webpack-common.dev.js
: Dev Env Configs (ie. HotModuleReplacementPlugin)
webpack-common.prod.js
: Prod Env Configs (ie. ExtractTextPlugin)
webpack.config.js
:
'use strict';
module.exports = env => {
return env === 'dev'
? require('./config/webpack-dev.config')
: require('./config/webpack-prod.config');
};
- Through create-react-app
- Manual by Node Packages
- 'npm i -D react react-dom'
- 'npm i -D babel babel-preset-react babel-preset-es2015'
- Create
.babelrc
file Options
{
"presets": ["es2015", "react"]
}
- Set-up Babel
npm install --save-dev babel-loader babel-core
Container Components Describe how things work
- Almost always the parents of Presentational Components.
- Source the data and deal with state.
- State is then passed to Presentational Components as props and is then rendered into views.
Presentational Components Describe how things look
- Managing its own props.
- They have no idea how the props they received came to be.
- They have no idea about state.
- Never change the prop data itself.
Stateful
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Component extends Component {
render() {
return (
);
}
}
Component.propTypes = {};
Component.defaultProps = {};
export default Component;
Stateless
- Faster in performance
- No Class Needed
- No this Keyword
- Focus on the UI rather than behavior
- Don’t support state or lifecycle methods
- State should be managed by higher-level "container" components
- Easier to test
import React from 'react';
const Component = (props) => {
return (
{props.attribute}
);
};
export default Component;
- Both Model data for components.
- Both props and state of a parent component will become just props to their child component.
Props:
Props (short for properties), are a Component's configuration.
A Component cannot change its props but it is responsible for putting together the props of its child Components.
- Data flows from parent to child. Defined in child component (this.props.name) and get value in parent component.
- Props are immutable.
- Component can have default props so that props are set even if a parent component doesn’t pass props down to the child.
State:
State, is an object that is owned by the component where it is declared used to change the component.
A Component manages its own state internally and has no business fiddling with the state of its children.
- Data flows from child to parent.
- Like when user input some new data to the child component.
- State is mutable and private.
- State is used so that a component can keep track of information in between any renders that it does.
- setState it updates the state object and then re-renders
- how a component's data looks at a given point in time
props | state | |
---|---|---|
Can get initial value from parent Component? | Yes | Yes |
Can be changed by parent Component? | Yes | No |
Can set default values inside Component?* | Yes | Yes |
Can change inside Component? | No | Yes |
Can set initial value for child Components? | Yes | Yes |
Can change in child Components? | Yes | No |
Note
- Both props and state initial values received from parents override default values defined inside a Component.
- Both props and state are plain JS objects
- Both props and state changes trigger a render update
- props :: Parent => Child Component (Read through child component by
this.props
) - state :: Created inside Component (Write by
this.setState()
, Read bythis.state
)
Presentational Components | Container Components | |
---|---|---|
Type | Function (Stateless, Pure) | Class (Stateful, Impure) |
Purpose | How things look (markup, styles) | How things work (data fetching, state updates) |
To read data | Read data from props | Subscribe to Redux state |
To change data | Invoke callbacks from props | Dispatch Redux actions |
Access to State | No | Yes (this.state.XXX ) |
Access to props | Yes (props.XXX ) |
Yes (this.props.XXX ) |
Lifecycle Hooks | No | Yes |
Container Component
A container component is a component that is connected to the store and aware of application state and changes to that state.
It takes that state and passes aspects of it to presentational components as props.
Presentational Component
Presentational components are not aware of the store or our application state. They know about their own props.
They respond to user actions by invoking callback functions that their container component passed them.
import React from 'react';
export default () => <h1>Simple Stateless Component</h1>;
- if you want to use
this
in a react class component function, you need to use Function Expression (not Function Declaration)
declaredFunc() {
console.log(this); // undefined
}
expressedFunc = () => {
console.log(this); // the react class
};
Component Lifecycle
when an instance of a component is being created and inserted into the DOM
constructor()
constructor(props) { super(props); // Don't call this.setState() here! this.state = { counter: 0 }; this.handleClick = this.handleClick.bind(this); }
render()
componentDidMount()
caused by changes to props or state, when a component is being re-rendered
shouldComponentUpdate()
render()
render() will not be invoked if shouldComponentUpdate() returns false.componentDidUpdate()
when a component is being removed from the DOM
componentWillUnmount()
when there is an error during rendering, in a lifecycle method, or in the constructor of any child component
componentDidCatch()
setState()
forceUpdate()
defaultProps
Class PropertiesdisplayName
Class Properties- ``
Mounting
constructor()
- The constructor is the right place to initialize state. If you don't initialize state and you don't bind methods, you don't need to implement a constructor for your React component.
- Call
super(props)
in constructor method before any other statement. Otherwise, this.props will be undefined in the constructor. super()
give the keywordthis
the context within the component rather than its parent.
componentWillMount()
render()
componentDidMount()
Updating
componentWillReceiveProps()
shouldComponentUpdate()
componentWillUpdate()
render()
componentDidUpdate()
Unmounting
componentWillUnmount()
Other APIs
setState()
forceUpdate()
Class Properties#
defaultProps
displayName
Instance Properties
props
state
props.children
- Some components don't know their children ahead of time, use the special children prop to pass children elements directly into their output.
- In order to access nested values or components in a component, we can use props.children.
render() {
return (
<div className="App">
<h1>React Project is Up.</h1>
</div>
);
}
render() {
return React.createElement('div', {className: 'App'}, React.createElement('h1', null, 'React Project is Up.'));
}
this.constructor.name
will gives you name of react class addressed bythis
keyword.
text(props, propName, component){
if(!(propName in props)){
return new Error(`missing ${propName}`)
}
if(props[propName].length < 7){
return new Error(`${propName} was too short`)
}
}
bind()
- Creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
- Bind in Constructor
this.eventHandler = this.eventHandler.bind(this);
React Synthetic Event System
-
Clipboard Events
onCopy
onCut
onPaste
-
Keyboard Events
onKeyDown
onKeyPress
onKeyUp
-
Focus Events
onFocus
onBlur
-
Form Events
onChange
onInput
onSubmit
-
Mouse Events
onClick
onContextMenu
onDoubleClick
onDrag
onDragEnd
onDragEnter
onDragExit
onDragLeave
onDragOver
onDragStart
onDrop
onMouseDown
onMouseEnter
onMouseLeave
onMouseMove
onMouseOut
onMouseOver
onMouseUp
-
Touch Events
onTouchCancel
onTouchEnd
onTouchMove
onTouchStart
-
UI Events
onScroll
-
Wheel Events
onWheel
In the typical React dataflow, props are the only way that parent components interact with their children.
However, there are a few cases where you need to imperatively modify a child outside of the typical dataflow.
-
The ref attribute takes a callback function, and the callback will be executed immediately after the component is mounted or unmounted.
-
For Component:
a: this.a.value
in update method.
in Parent Component:
ref={node => this.a = node}
- For Component's Child:
a: this.a.refs.a.value
in update method.
in Parent Component:
ref={component => this.a = component}
ref='a'
in Child Component
/* Data (Data) */
const DATA_1 = {
attr_1: "value_1",
attr_2: "value_2"
};
const DATA_2 = {
attr_1: "value_1",
attr_2: "value_2"
};
/* Children (Template) */
class Child extends Component {
render() {
return (
<div>
<h3>{this.props.data.attr_1}</h3>
<h5>{this.props.data.attr_1}</h5>
</div>
);
}
}
/* Parent (Display) */
class Parent extends Component {
render() {
return (
<div>
<Child data={DATA_1} />
<Child data={DATA_2} />
</div>
);
}
}
- Redux: Serves To Construct The Application State
- React: Provides The View To That Application State
- The state of your whole application is stored in an object tree within a single store.
- The only way to change the state is to emit an action, an object describing what happened.
- To specify how the state tree is transformed by actions, you write pure reducers.
# | Presentational Components | Container Components |
---|---|---|
Purpose | How things look (markup, styles) | How things work (data fetching, state updates) |
Aware of Redux | No | Yes |
To read data | Read data from props | Subscribe to Redux state |
To change data | Invoke callbacks from props | Dispatch Redux actions |
Written | By hand | Usually generated by React Redux |
- Always begin with the presentational components, then if needed promote them into container components.
-
Application State, get generated by
reducer functions
. -
A
container
(smart component) will be connected to application state by:- importing
connect
method fromreact-redux
- defining
mapStateToProps
method to return the application state as props for the container which cares about the state changes. - exporting connect method value for the container and
mapStateToProps
- importing
-
Redux
generate the state object and maps that state as a props for the container component. as the state is updated,container
will re-rendered with new state.
- User interact with application and cause directly/indirectly an
event
being triggered (React -> Redux) - Redux will call action creator function which returns an object
action
, containing type of event and the changed object (Redux) - Action object will automatically being
sent to ALL reducers
(Redux) - If reducers function, care about the action, will set state with the updates in action and
return the new state
(Redux -> React) - Once state is changed, all container components will be notified and those related ones will be
re-rendered with new state
. (React)