React.createElement()
function, giving us expressiveness of JavaScript along with HTML like template syntax.<h1>
tag is returned as JavaScript function to the render function.class App extends React.Component {
render() {
return(
<div>
<h1>{'Welcome to React world!'}</h1>
</div>
)
}
}
function Greeting({ message }) {
return <h1>{`Hello, ${message}`}</h1>
}
class Greeting extends React.Component {
render() {
return <h1>{`Hello, ${this.props.message}`}</h1>
}
}
React.PureComponent
is exactly the same as React.Component
except that it handles the shouldComponentUpdate()
method for you. When props or state changes, PureComponent will do a shallow comparison on both props and state. Component on the other hand won't compare current props and state to next out of the box. Thus, the component will re-render by default whenever shouldComponentUpdate
is called. class User extends React.Component {
constructor(props) {
super(props)
this.state = {
message: 'Welcome to React world'
}
}
render() {
return (
<div>
<h1>{this.state.message}</h1>
</div>
)
}
}
render()
mandatorily. It returns a single React element which is the representation of the native DOM component. If more than one HTML element needs to be rendered, then they must be grouped together inside one enclosing tag such as <form>, <group>,<div>
etc. This function must be kept pure i.e., it must return the same result each time it is invoked. render()
method.<Element reactProp={'1'} />
props.reactProp
setState()
is asynchronous the callback function is used for any post action.setState({ name: 'John' }, () => console.log('The name has updated and component re-rendered'))
getState()
and dispatch()
are provided as parameters to the inner function.applyMiddleware()
method as shown below:import{ createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
//Note: this API requires redux@>=3.1.0
const store= createStore(
rootReducer,
applyMiddleware(thunk)
);
const EnhancedComponent = higherOrderComponent(WrappedComponent)
React.createElement()
functions to create React elements which are going to be used for the object representation of UI. Whereas cloneElement
is used to clone an element and pass it new props. function HOC(WrappedComponent) {
return class Test extends Component {
render() {
const newProps = {
title: 'New Header',
footer: false,
showFeatureX: false,
showFeatureY: true
}
return <WrappedComponent {...this.props} {...newProps} />
}
}
}
const {Provider, Consumer} = React.createContext(defaultValue)
class
is a keyword in JavaScript, and JSX is an extension of JavaScript. That's the principal reason why React uses className
instead of class
. Pass a string as the className
prop.render() {
return <span className={'menu navigation-menu'}>{'Menu'}</span>
}
function addTodo(text) {
return {
type: ADD_TODO,
text
}
}
<div>
is used to encapsulate multiple routes inside the Router. The ‘switch’ keyword is used when you want to display only a single route to be rendered amongst the several defined routes. The <switch>
tag when in use matches the typed URL with the defined routes in sequential order. When the first match is found, it renders the specified route. Thereby bypassing the remaining routes. DefinePlugin
strategy to set NODE_ENV
to production. This will strip out things like prototype approval and additional notices. Over that, it's likewise a smart thought to minify your code in light of the fact that React utilizes Uglify's dead-code end to strip out advancement just code and remarks, which will radically diminish the measure of your package. virtual DOM
object. It is nothing but can be considered as the lighter version of the true copy and is powerful in eliminating the complex code. It is also used as a Blue Print for performing several basic experiments. Many developers also use it while practicing this technology. unstable_handleError
method. It has been renamed to componentDidCatch
in React v16. React.PropTypes
moved to a prop-types
package since React v15.5) for type checking in the React applications. For large code bases, it is recommended to use static type checkers such as Flow or TypeScript, that perform type checking at compile time and provide auto-completion features. ReactDOM.render(element, container[, callback])
dangerouslySetInnerHTML
attribute is React's replacement for using innerHTML in the browser DOM. Just like innerHTML
, it is risky to use this attribute considering cross-site scripting (XSS) attacks. You just need to pass a __html
object as key and HTML text as value.dangerouslySetInnerHTML
attribute for setting HTML markup:function createMarkup() {
return { __html: 'First · Second' }
}
function MyComponent() {
return <div dangerouslySetInnerHTML={createMarkup()} />
}
componentWillMount()
lifecycle method. componentWillMount()
is invoked immediately before mounting occurs. It is called before render()
, therefore setting state in this method will not trigger a re-render. Avoid introducing any side-effects or subscriptions in this method. We need to make sure async calls for component initialization happened in componentDidMount()
instead of componentWillMount()
.componentDidMount() {
axios.get(`api/todos`)
.then((result) => {
this.setState({
messages: [...result.data]
})
})
}
moize
library can memoize the component in another component.import moize from 'moize'
import Component from './components/Component' // this module exports a non-memoized component
const MemoizedFoo = moize.react(Component)
const Consumer = () => {
<div>
{'I will memoize the following entry:'}
<MemoizedFoo/>
</div>
}
React.memo
. It provides a higher order component which memoizes component unless the props change. To use it, simply wrap the component using React.memo before you use it. const MemoComponent = React.memo(function MemoComponent(props) {
/* render using props */
});
OR
export default React.memo(MyFunctionComponent);
import ReactDOMServer from 'react-dom/server'
import App from './App'
ReactDOMServer.renderToString(<App />)
getDerivedStateFromProps()
lifecycle method is invoked after a component is instantiated as well as before it is re-rendered
. It can return an object to update state, or null
to indicate that the new props do not require any state updates.class MyComponent extends React.Component {
static getDerivedStateFromProps(props, state) {
// ...
}
}
componentDidUpdate()
covers all the use cases of componentWillReceiveProps()
PureRenderMixin
. You might be using it in some components to prevent unnecessary re-renders when the props and state are shallowly equal to the previous props and state:const PureRenderMixin = require('react-addons-pure-render-mixin')
const Button = React.createClass({
mixins: [PureRenderMixin],
// ...
})
render()
method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate()
.component.forceUpdate(callback)
forceUpdate()
and only read from this.props
and this.state
in render()
.react
package contains React.createElement()
, React.Component, React.Children,
and other helpers related to elements and component classes. You can think of these as the isomorphic or universal helpers that you need to build components. react-dom
package contains ReactDOM.render()
, and in react-dom/server we have server-side rendering support with ReactDOMServer.renderToString()
and ReactDOMServer.renderToStaticMarkup()
. <label>
element bound to a text input using the standard for attribute, then it produces HTML missing that attribute and prints a warning to the console.<label for={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
for
is a reserved keyword in JavaScript, use htmlFor
instead.<label htmlFor={'user'}>{'User'}</label>
<input type={'text'} id={'user'} />
<button style={{...styles.panel.button, ...styles.panel.submitButton}}>{'Submit'}</button>
<button style={[styles.panel.button, styles.panel.submitButton]}>{'Submit'}</button>
const REACT_VERSION = React.version
ReactDOM.render(
<div>{`React version: ${REACT_VERSION}`}</div>,
document.getElementById('app')
)
HTTPS=true
configuration. You can edit your package.json
scripts section:"scripts": {
"start": "set HTTPS=true && react-scripts start"
}
set HTTPS=true && npm start
history
object to record each page view:history.listen(function (location) {
window.ga('set', 'page', location.pathname + location.search)
window.ga('send', 'pageview', location.pathname + location.search)
})
eslint-plugin-react
. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types.eslint-plugin-jsx-a11y
, which will help fix common issues with accessibility. As JSX offers slightly different syntax to regular HTML, issues with alt
text and tabindex
, for example, will not be picked up by regular plugins.push()
will add a new location to the array and replace()
will replace the current location in the array with the new one.<Switch>
renders the first child <Route>
that matches. A <Route>
with no path always matches. So you just need to simply drop path attribute as below<Switch>
<Route exact path="/" component={Home}/>
<Route path="/user" component={User}/>
<Route component={NotFound} />
</Switch>
react-router
package provides <Redirect>
component in React Router. Rendering a <Redirect>
will navigate to a new location. Like server-side redirects, the new location will override the current location in the history stack.import React, { Component } from 'react'
import { Redirect } from 'react-router'
export default class LoginComponent extends Component {
render() {
if (this.state.isLoggedIn === true) {
return <Redirect to="/your/redirect/page" />
} else {
return <div>{'Login Please'}</div>
}
}
}
componentDidMount, componentDidUpdate, componentWillUnmount
. Instead, we will use built-in hooks like useEffect
....
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...
const setCount = () => {
setCounter(count + 1);
setMoreStuff(...);
...
};
useState
is one of build-in react hooks. useState(0)
returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state.
We can use the setCounter
method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.
jsdom
environment. It's often used for testing components. React
is a JavaScript library, supporting both front end web and being run on the server, for building user interfaces and web applications.React Native
is a mobile framework that compiles to native app components, allowing you to build native mobile applications (iOS, Android, and Windows) in JavaScript that allows you to use React to build your components, and implements React under the hood.trade work fetchAccount(id) {
return dispatch => {
dispatch(setLoadingAccountState())/Show a stacking spinner
get(‘/account/${id}’, (reaction) => {
dispatch(doneFetchingAccount())/Hide stacking spinner
on the off chance that (response.status === 200) {
dispatch(setAccount(response.json))/Use an ordinary capacity to set the got state
} else {
dispatch(someError)
}
})
}
}
work setAccount(data) {
return { type: ‘SET_Account’, information: information }
}​