Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
39 views

React - Js Cheatsheet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

React - Js Cheatsheet

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

4/24/24, 2:44 AM React.

js cheatsheet

DEVHINTS.IO Edit

Get 10 Free Images From Adobe


Stock. Start Now.

React.js cheatsheet ads via Carbon

React is a JavaScript library for building user interfaces. This guide targets React v15 to v16.

Components Properties Nesting

import React from 'react' <Video fullscreen={true} autoplay={fals class Info extends Component {
import ReactDOM from 'react-dom' render () {
const { avatar, username } = this.p

class Hello extends React.Component { render () {


return <div>
render () { this.props.fullscreen
<UserAvatar src={avatar} />
return <div className='message-box' const { fullscreen, autoplay } = this
<UserProfile username={username}
Hello {this.props.name} ··· </div>
</div> } }
}
}
}

Use this.props to access properties passed


to the component. As of React v16.2.0, fragments can be used to
const el = document.body
ReactDOM.render(<Hello name='John' />, return multiple children without adding extra
See: Properties
wrapping nodes to the DOM.

import React, {
Use the React.js jsfiddle to start hacking. (or
Component,
the unofficial jsbin) States Fragment
} from 'react'
constructor(props) {
super(props) class Info extends Component {
this.state = { username: undefined } render () {
Import multiple exports
} const { avatar, username } = this.p

import React, {Component} from 'react' return (


import ReactDOM from 'react-dom' <Fragment>
this.setState({ username: 'rstacruz' }) <UserAvatar src={avatar} />
<UserProfile username={username
</Fragment>
class Hello extends Component {
)
... render () {
}
} this.state.username
}
const { username } = this.state
···
}

Nest components to separate concerns.


Use states (this.state) to manage dynamic
See: Composing Components
data.

With Babel you can use proposal-class-fields


and get rid of constructor

class Hello extends Component {


state = { username: undefined };
...
}

See: States

https://devhints.io/react 1/9
4/24/24, 2:44 AM React.js cheatsheet

Children

<AlertBox>
<h1>You have pending notifications</h
</AlertBox>

class AlertBox extends Component {


render () {
return <div className='alert-box'>
{this.props.children}
</div>
}
}

Children are passed as the children


property.

Defaults

Setting default props Setting default state

Hello.defaultProps = { class Hello extends Component {


color: 'blue' constructor (props) {
} super(props)
this.state = { visible: true }
}
See: defaultProps }

Set the default state in the constructor().

And without constructor using Babel with proposal-class-fields.

class Hello extends Component {


state = { visible: true }
}

See: Setting the default state

Other components

https://devhints.io/react 2/9
4/24/24, 2:44 AM React.js cheatsheet

Functional components Pure components Component API

function MyComponent ({ name }) { import React, {PureComponent} from 'rea this.forceUpdate()


return <div className='message-box'>
Hello {name} class MessageBox extends PureComponent
this.setState({ ... })
</div> ···
this.setState(state => { ... })
} }

this.state
this.props
Functional components have no state. Also, Performance-optimized version of
their props are passed as the first parameter React.Component. Doesn’t rerender if
These methods and properties are available
to a function. props/state hasn’t changed.
for Component instances.
See: Function and Class Components See: Pure components
See: Component API

Lifecycle

Mounting Updating

constructor (props) Before rendering # componentDidUpdate (prevProps, prevState, snapshot) Use setState()
here, but
componentWillMount() Don’t use this # remember to
compare props
render() Render #
shouldComponentUpdate (newProps, newState) Skips render()
componentDidMount() After rendering (DOM available) #
if returns false

componentWillUnmount() Before DOM removal #


render() Render

componentDidCatch() Catch errors (16+) #


componentDidUpdate (prevProps, prevState) Operate on the
DOM here
Set initial the state on constructor(). Add DOM event handlers, timers
(etc) on componentDidMount(), then remove them on Called when parents change properties and .setState(). These are not
componentWillUnmount(). called for initial renders.

See: Component specs

Hooks (New)

https://devhints.io/react 3/9
4/24/24, 2:44 AM React.js cheatsheet

State Hook Effect hook

import React, { useState } from 'react'; import React, { useState, useEffect } from 'react';

function Example() { function Example() {


// Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0);
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
return ( useEffect(() => {
<div> // Update the document title using the browser API
<p>You clicked {count} times</p> document.title = `You clicked ${count} times`;
<button onClick={() => setCount(count + 1)}> }, [count]);
Click me
</button> return (
</div> <div>
); <p>You clicked {count} times</p>
} <button onClick={() => setCount(count + 1)}>
Click me
</button>
Hooks are a new addition in React 16.8. </div>
);
See: Hooks at a Glance
}

If you’re familiar with React class lifecycle methods, you can think of
useEffect Hook as componentDidMount, componentDidUpdate, and
Declaring multiple state variables
componentWillUnmount combined.

import React, { useState } from 'react'; By default, React runs the effects after every render — including the first
render.
function ExampleWithManyStates() {
// Declare multiple state variables!
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
const [todos, setTodos] = useState([{ text: 'Learn Hooks' }
// ...
}

https://devhints.io/react 4/9
4/24/24, 2:44 AM React.js cheatsheet

Building your own hooks Hooks API Reference

Define FriendStatus
Also see: Hooks FAQ
import React, { useState, useEffect } from 'react';
Basic Hooks
function FriendStatus(props) {
useState(initialState)
const [isOnline, setIsOnline] = useState(null);

useEffect(() => { … })
useEffect(() => {
function handleStatusChange(status) {
useContext(MyContext) value returned from React.createContext
setIsOnline(status.isOnline);
}
Full details: Basic Hooks
ChatAPI.subscribeToFriendStatus(props.friend.id, handleSt
return () => { Additional Hooks
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, ha
}; useReducer(reducer, initialArg, init)
}, [props.friend.id]);
useCallback(() => { … })
if (isOnline === null) {
return 'Loading...'; useMemo(() => { … })
}
return isOnline ? 'Online' : 'Offline'; useRef(initialValue)
}
useImperativeHandle(ref, () => { … })

useLayoutEffect identical to useEffect, but it


Effects may also optionally specify how to “clean up” after them by fires synchronously after all
returning a function. DOM mutations

Use FriendStatus useDebugValue(value) display a label for custom


hooks in React DevTools
function FriendStatus(props) {
const isOnline = useFriendStatus(props.friend.id);
Full details: Additional Hooks

if (isOnline === null) {


return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}

See: Building Your Own Hooks

DOM nodes

References DOM Events

class MyComponent extends Component { class MyComponent extends Component {


render () { render () {
return <div> <input type="text"
<input ref={el => this.input = el} /> value={this.state.value}
</div> onChange={event => this.onChange(event)} />
} }

componentDidMount () { onChange (event) {


this.input.focus() this.setState({ value: event.target.value })
} }
} }

Allows access to DOM nodes. Pass functions to attributes like onChange.

See: Refs and the DOM See: Events

https://devhints.io/react 5/9
4/24/24, 2:44 AM React.js cheatsheet

Other features

Transferring props Top-level API

<VideoPlayer src="video.mp4" /> React.createClass({ ... })


React.isValidElement(c)

class VideoPlayer extends Component {


render () { ReactDOM.render(<Component />, domnode, [callback])
return <VideoEmbed {...this.props} /> ReactDOM.unmountComponentAtNode(domnode)
}
}
ReactDOMServer.renderToString(<Component />)
ReactDOMServer.renderToStaticMarkup(<Component />)
Propagates src="..." down to the sub-component.

See Transferring props There are more, but these are most common.

See: React top-level API

JSX patterns

Style shorthand Lists

const style = { height: 10 } class TodoList extends Component {


return <div style={style}></div> render () {
const { items } = this.props

return <div style={{ margin: 0, padding: 0 }}></div>


return <ul>
{items.map(item =>
See: Inline styles <TodoItem item={item} key={item.key} />)}
</ul>
}
}

Inner HTML
Always supply a key property.

function markdownify() { return "<p>...</p>"; }


<div dangerouslySetInnerHTML={{__html: markdownify()}} />

See: Dangerously set innerHTML


Conditionals

<Fragment>
{showMyComponent
? <MyComponent />
: <OtherComponent />}
</Fragment>

Short-circuit evaluation

<Fragment>
{showPopup && <Popup />}
...
</Fragment>

New features

https://devhints.io/react 6/9
4/24/24, 2:44 AM React.js cheatsheet

Returning multiple elements Returning strings Portals

You can return multiple elements as arrays or render() { render () {


return 'Look ma, no spans!'; return React.createPortal(
fragments.
} this.props.children,
document.getElementById('menu')
Arrays
)
You can return just a string. }
render () {
// Don't forget the keys! See: Fragments and strings
return [
This renders this.props.children into any
<li key="A">First item</li>,
location in the DOM.
<li key="B">Second item</li>
] See: Portals
} Errors

Fragments class MyComponent extends Component {


···
render () {
componentDidCatch (error, info) { Hydration
return (
this.setState({ error })
<Fragment>
} const el = document.getElementById('app
<li>First item</li>
} ReactDOM.hydrate(<App />, el)
<li>Second item</li>
</Fragment>
) Catch errors via componentDidCatch. (React
}
16+) Use ReactDOM.hydrate instead of using
See: Error handling in React 16 ReactDOM.render if you’re rendering over
See: Fragments and strings the output of ReactDOMServer.

See: Hydrate

Property validation

https://devhints.io/react 7/9
4/24/24, 2:44 AM React.js cheatsheet

PropTypes Basic types Arrays and objects

import PropTypes from 'prop-types' MyComponent.propTypes = { MyCo.propTypes = {


email: PropTypes.string, list: PropTypes.array,
seats: PropTypes.number, ages: PropTypes.arrayOf(PropTypes.num
See: Typechecking with PropTypes callback: PropTypes.func, user: PropTypes.object,
isClosed: PropTypes.bool, user: PropTypes.objectOf(PropTypes.nu
any Anything any: PropTypes.any message: PropTypes.instanceOf(Message
} }
Basic

string
MyCo.propTypes = {
number
Required types user: PropTypes.shape({
name: PropTypes.string,
func Function age: PropTypes.number
MyCo.propTypes = {
})
bool True or false name: PropTypes.string.isRequired
}
}
Enum
Use .array[Of], .object[Of],
oneOf(any) Enum types
.instanceOf, .shape.

oneOfType(type array) Union Elements


Array
MyCo.propTypes = {
array // React element Custom validation
element: PropTypes.element,
arrayOf(…)
MyCo.propTypes = {
// num, string, element, or an array
Object customProp: (props, key, componentNam
node: PropTypes.node
if (!/matchme/.test(props[key])) {
}
object return new Error('Validation fail
}
objectOf(…) Object with values of a }
certain type }

instanceOf(…) Instance of a class


Enumerables (oneOf)
shape(…)
MyCo.propTypes = {
Elements direction: PropTypes.oneOf([
'left', 'right'
element React element
])
}
node DOM node

Required

(···).isRequired Required

Also see

React website (reactjs.org)

React cheatsheet (reactcheatsheet.com)

Awesome React (github.com)

React v0.14 cheatsheet Legacy version

https://devhints.io/react 8/9
4/24/24, 2:44 AM React.js cheatsheet

0 Comments for this cheatsheet. Write yours!

devhints.io / Search 357+ cheatsheets

Other React cheatsheets Top cheatsheets

Redux Enzyme Elixir ES2015+


cheatsheet cheatsheet cheatsheet cheatsheet

Over 357 curated


cheatsheets, by developers Enzyme v2 Awesome Redux Vim Vimdiff
for developers. cheatsheet cheatsheet cheatsheet cheatsheet

Devhints home
Flux architecture React-router Vim scripting Vue.js
cheatsheet cheatsheet cheatsheet cheatsheet

https://devhints.io/react 9/9

You might also like