Sometimes, it can take 30 minutes to create a quick interface using React. But other times, it can take hours.
If you often forget the names of methods, properties, or the functionality they provide, it can become irritating to have to leave your code editor just for a Google search. You may be thinking, is it really that hard to type in a couple of letters and get the answers you want? Well, absolutely not. But if this happens more than once, then maybe it’s time to acquire a cheat sheet so that you don’t have to leave your code editor anymore. Having a cheat sheet next to you will certainly save you some time in the long run!
Here’s a cheat sheet you can use:
While you’re looking at the cheat sheet, just keep in mind that you can:
1. Generate the cheat sheet into a downloadable PDF/JPEG, or you can bookmark the page and come back to it at a later time.
2. If you don't like how the columns are ordered, you can drag and re-order them before you generate the cheat sheet.
3. You can select any of the code syntax themes in the select box to generate in the cheat sheet (there are about 25 themes you can choose from):
I’ll go ahead and put this in a public repo if anyone needs it. I also just began this yesterday, and so it may not be a perfect cheat sheet yet.
Also, my goal was to fit all of this into one page, but there was too much information. If anyone has any suggestions on which parts to swap/remove, feel free to let me know.
The changes will also stay after you close your browser so that you don’t have to redo everything. Here’s a full list of what’s in the cheat sheet so far (I will keep updating the cheat sheet over time).
// Does not support key attribute const App = () => ( <> <MyComponent /> </> ) // Supports key attribute const App = () => ( <React.Fragment key="abc123"> <MyComponent /> </React.Fragment> )
const App = () => 'a basic string' // string const App = () => 1234567890 // number const App = () => true // boolean const App = () => null // null const App = () => <div /> // react element const App = () => <MyComponent /> // component const App = () => [ // array 'a basic string', 1234567890, true, null, <div />, <MyComponent />, ]
class MyErrorBoundary extends React.Component { state = { hasError: false } componentDidCatch(error, info) {...} render() { if (this.state.hasError) return <SomeErrorUI /> return this.props.children } }const App = () => (
<MyErrorBoundary>
<Main />
</MyErrorBoundary>
)
// Returning object = New props require state update
// Returning null = New props do not require state update
class MyComponent extends React.Component {
static getDerivedStateFromProps(props, state) {…}
state = {…}
}// Return value is passed as 3rd argument to componentDidUpdate
class MyComponent extends React.Component {
static getSnapshotBeforeUpdate(prevProps, prevState) {…}
}// Listening to context from a class component
import SomeContext from ‘…/SomeContext’
class MyCompmonent extends React.Component {
static contextType = SomeContext
componentDidMount() { console.log(this.context) }
}// Enables rendering fallback UI before render completes
class MyComponent extends React.Component {
state getDerivedStateFromError() {…}
state = { error: null }
componentDidCatch(error, info) {…}
}
// Class component state
class MyComponent extends React.Component {
state = { loaded: false }
componentDidMount = () => this.setState({ loaded: true })
render() {
if (!this.state.loaded) return null
return <div {…this.props} />
}
}// Function component state (useState/useReducer)
const MyComponent = (props) => {
// With useState
const [loaded, setLoaded] = React.useState(false)
// With useReducer
const [state, dispatch] = React.useReducer(reducer, initialState)
if (!loaded) return null
React.useEffect(() => void setLoaded(true))
return <div {…props} />
// Ways to render Card
const Card = (props) => <div {…props} />const App = ({ items = [] }) => {
const renderCard = (props) => <Card {…props} />
return items.map(renderCard)
// or return items.map((props) => renderCard(props))
}const App = (props) => <Card {…props} />
class App extends React.Component {
render() {
return <Card {…this.props} />
}
}const MyComp = ({ component: Component }) => <Component />
const App = () => <MyComp component={Card} />
// Function component
const MyComponent = (props) => <div {…props} />
MyComponent.defaultProps = { fruit: ‘apple’ }// Class component
class MyComponent extends React.Component {
static defaultProps = { fruit: ‘apple’ }render() {
return <div {…this.props} />
}
}
// createContext (React v16.3)
const WeatherContext = React.createContext({ day: 3 })const App = ({ children }) => {
const [weather, setWeather] = React.useState(null)
const [error, setError] = React.useState(null)React.useEffect(() => {
api.getWeather(…)
.then(setWeather)
.catch(setError)
}, [])const contextValue = { weather, error }
return (
<WeatherContext.Provider value={contextValue}>
{children}
</WeatherContext.Provider>
)
}
const SomeChild = () => {
const { weather } = React.useContext(WeatherContext)
console.log(weather)
return null
}// createRef (Obtain a reference to a react node) (React v16.3)
const App = () => {
const ref = React.createRef()
React.useEffect(() => { console.log(ref.current) }, [])
return <div ref={ref} />
}// forwardRef (Pass the ref down to a child) (React v16.3)
const Remote = React.forwardRef((props, ref) => (
<div ref={ref} {…props} />
))const App = () => {
const ref = React.createRef()
return <Remote ref={ref} />
}// memo (Optimize your components to avoid wasteful renders) (React v16.6)
const App = () => {…}
const propsAreEqual = (props, nextProps) => {
return props.id === nextProps.id
} // Does not re-render if id is the same
export default React.memo(App, propsAreEqual)
// default export
const App = (props) => <div {…props} />
export default App
import App from ‘./App’// named export
export const App = (props) => <div {…props} />
import { App } from ‘./App’
onPointerUp onPointerDown
onPointerMove onPointerCancel
onGotPointerCapture onLostPointerCapture
onPointerEnter onPointerLeave
onPointerOver onPointerOutconst App = () => {
const onPointerDown = (e) => console.log(e.pointerId)
return <div onPointerDown={onPointerDown} />
}
// lazy -> Dynamic import. Reduces bundle size
// + Code splitting
const MyComponent = React.lazy(() => import('./MyComponent))
const App = () => <MyComponent />// Suspend rendering while components are waiting for something
// + Code splitting
import LoadingSpinner from ‘…/LoadingSpinner’const App = () => (
<React.Suspense fallback={<LoadingSpinner />}>
<MyComponent />
</React.Suspense>
)
const App = () => (
<React.StrictMode>
<div>
<MyComponent />
<OtherComponent />
</div>
</React.StrictMode>
)
act
Test Utility (React v16.9)import { act } from ‘react-dom/test-utils’
import MyComponent from ‘./MyComponent’const container = document.createElement(‘div’)
// Synchronous
it(‘renders and adds new item to array’, () => {
act(() => {
ReactDOM.render(<MyComponent />, container)
})
const btn = container.querySelector(‘button’)
expect(btn.textContent).toBe(‘one item’)
act(() => {
button.dispatchEvent(new MouseEvent(‘click’, { bubbles: true }))
})
expect(btn.textContent).toBe(‘two items’)
})// Asynchronous
it(‘does stuff’, async () => {
await act(async () => {
// code
})
})
Check out the cheat sheet here.
And that’s the end of this post! I hope you found this to be useful and lookout for more in the future!
Thanks for reading ❤
If you liked this post, share it with all of your programming buddies!
Follow us on Facebook | Twitter
☞ React - The Complete Guide (incl Hooks, React Router, Redux)
☞ Modern React with Redux [2019 Update]
☞ Best 50 React Interview Questions for Frontend Developers in 2019
☞ JavaScript Basics Before You Learn React
☞ Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)
☞ Reactjs vs. Angularjs — Which Is Best For Web Development
☞ React + TypeScript : Why and How
☞ How To Write Better Code in React
☞ React Router: Add the Power of Navigation
☞ Getting started with React Router
☞ Using React Router for optimizing React apps
☞ Creating RESTful APIs with NodeJS and MongoDB Tutorial
#reactjs #javascript #web-development