test
spot_img
HomeEducationReact Js Cheat Sheet : Do You Actually Want It? This Will...

React Js Cheat Sheet : Do You Actually Want It? This Will Assist You Resolve! Acquire US

React is a JavaScript library for constructing person interfaces. This information targets React v15 to v16. React permits builders to create massive net functions that may change information, with out reloading the web page. The primary function of React is to be quick, scalable, and easy. It really works solely on person interfaces within the utility. It may appear overwhelming for a newbie to be taught the React framework. In spite of everything, it has gone by way of a number of adjustments because it was first launched round 2013. Right here’s a React JS cheat sheetnot a full tutorial however a simple-to-understand and concise overview on what it takes to be taught React fundamentals.

I’ve put collectively an excellent useful cheat sheet to present you a whole overview of all the React ideas you could know in 2022.

What’s React?

ReactJs is JavaScript library designed to create single-page functions with reusable UI elements.

React shops the knowledge DOM by making a digital DOM in its reminiscence. Earlier than it renders the DOM nodes onto the browser, it checks for adjustments between its previous and current digital DOM. If there’s a change (i.e. some textual content content material up to date), it is going to replace its digital DOM after which renders to the true DOM on the browser. See diagram under for visualization.

React Parts

Parts are one of many constructing blocks of a React App. They’re mainly React features that returns an HTML ingredient. Consider them as a big HTML blocks of code that independently does a sure perform for the app. Just like the navigation bar or the panels.

In React, all these elements are structured as nodes within the Digital DOM. It’ll render onto the browser in response to how we specify them to seem like.

import React from 'react'
import ReactDOM from 'react-dom'
class Howdy extends React.Part 
  render () 
    return <div className="message-box">
      Howdy this.props.identify
    </div>
  

const el = doc.physique
ReactDOM.render(<Howdy identify="John" />, el)

Use the React.js jsfiddle to begin hacking. (or the unofficial jsbin)

Import a number of exports

import React, Part from 'react'
import ReactDOM from 'react-dom'
class Howdy extends Part 
  ...

Properties

<Video fullscreen=true autoplay=false />
render () 
  this.props.fullscreen
  const  fullscreen, autoplay  = this.props
  ···

 
 
Use this.props to entry properties handed to the part.

See: Properties

States

render () 
  this.state.username
  const  username  = this.state
  ···

Use states (this.state) to handle dynamic information.

With Babel you should use proposal-class-fields and eliminate constructor.

class Howdy extends Part 
  state =  username: undefined ;
  ...

Nesting

class Information extends Part 
  render () 
    const  avatar, username  = this.props

    return <div>
      <UserAvatar src=avatar />
      <UserProfile username=username />
    </div>
  

As of React v16.2.0, fragments can be utilized to return a number of youngsters with out including additional wrapping nodes to the DOM.

import React, 
  Part,
  Fragment
 from 'react'

class Information extends Part 
  render () 
    const  avatar, username  = this.props

    return (
      <Fragment>
        <UserAvatar src=avatar />
        <UserProfile username=username />
      </Fragment>
    )
  

Youngsters

class AlertBox extends Part 
  render () 
    return 

this.props.youngsters

Youngsters are handed because the youngsters property.

Defaults

Howdy.defaultProps = 
  coloration: 'blue'

See: defaultProps

Setting default state

class Howdy extends Part 
  constructor (props) 
    tremendous(props)
    this.state =  seen: true 
  

Set the default state within the constructor().

And with out constructor utilizing Babel with proposal-class-fields.

class Howdy extends Part 
  state =  seen: true 

See: Setting the default state

Different elements

Functional components

function MyComponent ( name ) 
  return <div className="message-box">
    Hello name
  </div>

Functional components have no state. Also, their props are passed as the first parameter to a function.

See: Function and Class Components

Pure components

import React, PureComponent from 'react'

class MessageBox extends PureComponent 
  ···

Performance-optimized version of React.Component. Doesn’t rerender if props/state hasn’t changed.

See: Pure components

Component API

this.forceUpdate()
this.setState( ... )
this.setState(state =>  ... )
this.state
this.props

These methods and properties are available for Component instances.

See: Component API

Lifecycle

Mounting

MethodDescription
constructor (props)Before rendering #
componentWillMount()Don’t use this #
render()Render #
componentDidMount()After rendering (DOM out there) #
componentWillUnmount()Earlier than DOM removing #
componentDidCatch()Catch errors (16+) #

Set preliminary the state on constructor().
Add DOM occasion handlers, timers (and so on) on componentDidMount(), then take away them on componentWillUnmount().

Updating

MethodDescription
componentDidUpdate (prevProps, prevState, snapshot)Use setState() here, but remember to compare props
shouldComponentUpdate (newProps, newState)Skips render() if returns false
render()Render
componentDidUpdate (prevProps, prevState)Operate on the DOM here

Called when parents change properties and .setState(). These are not called for initial renders.

See: Component specs

Hooks (New)

State Hook

import React,  useState  from 'react';

function Example() 
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked count times</p>
      <button onClick=() => setCount(count + 1)>
        Click me
      </button>
    </div>
  );

Hooks are a new addition in React 16.8.

See: Hooks at a Glance

Declaring multiple state variables

function ExampleWithManyStates() 
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([ text: 'Learn Hooks' ]);
  // ...

Effect hook

import React,  useState, useEffect  from 'react';

function Example() 
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => 
    // Update the document title using the browser API
    document.title = `You clicked $count times`;
  , [count]);

  return (
    <div>
      <p>You clicked count times</p>
      <button onClick=() => setCount(count + 1)>
        Click me
      </button>
    </div>
  );

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMountcomponentDidUpdate, and componentWillUnmount combined.

By default, React runs the effects after every render — including the first render.

Building your own hooks

Define FriendStatus

import React,  useState, useEffect  from 'react';

function FriendStatus(props) 
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => 
    function handleStatusChange(status) 
      setIsOnline(status.isOnline);
    

    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => 
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    ;
  , [props.friend.id]);

  if (isOnline === null) 
    return 'Loading...';
  
  return isOnline ? 'Online' : 'Offline';

Effects may also optionally specify how to “clean up” after them by returning a function.

Use FriendStatus

function FriendStatus(props) 
  const isOnline = useFriendStatus(props.friend.id);

  if (isOnline === null) 
    return 'Loading...';
  
  return isOnline ? 'Online' : 'Offline';

See: Building Your Own Hooks

Hooks API Reference

Also see: Hooks FAQ

Basic Hooks

HookDescription
useState(initialState)
useEffect(() => … )
useContext(MyContext)value returned from React.createContext

Full details: Basic Hooks

Additional Hooks

HookDescription
useReducer(reducer, initialArg, init)
useCallback(() => … )
useMemo(() => … )
useRef(initialValue)
useImperativeHandle(ref, () => … )
useLayoutEffectidentical to useEffect, but it fires synchronously after all DOM mutations
useDebugValue(value)display a label for custom hooks in React DevTools

Full details: Additional Hooks

DOM nodes

References

class MyComponent extends Component 
  render () 
    return <div>
      <input ref=el => this.input = el />
    </div>
  

  componentDidMount () 
    this.input.focus()
  

Allows access to DOM nodes.

See: Refs and the DOM

DOM Events

class MyComponent extends Component 
  render () 
    <input type="text"
        value=this.state.value
        onChange=event => this.onChange(event) />
  

  onChange (event) 
    this.setState( value: event.target.value )
  

Pass functions to attributes like onChange.

See: Events

Different options

Transferring props

<VideoPlayer src=" />
class VideoPlayer extends Component 
  render () 
    return <VideoEmbed ...this.props />
  

Propagates src="https://logicalidea.co/react-js-cheat-sheet/..." down to the sub-component.

See Transferring props

Top-level API

React.createClass( ... )
React.isValidElement(c)
ReactDOM.render(<Component />, domnode, [callback])
ReactDOM.unmountComponentAtNode(domnode)
ReactDOMServer.renderToString(<Component />)
ReactDOMServer.renderToStaticMarkup(<Component />)

There are more, but these are most common.

See: React top-level API

JSX patterns

Style shorthand

const style =  height: 10 
return <div style=style></div>
return <div style= margin: 0, padding: 0 ></div>

See: Inline styles

Inner HTML

function markdownify()  return "<p>...</p>"; 
<div dangerouslySetInnerHTML=__html: markdownify() />

See: Dangerously set innerHTML

Lists

class TodoList extends Component 
  render () 
    const  items  = this.props

    return <ul>
      items.map(item =>
        <TodoItem item=item key=item.key />)
    </ul>
  

Always supply a key property.

Conditionals

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

Short-circuit evaluation

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

New features

Returning multiple elements

You can return multiple elements as arrays or fragments.

Arrays

render () 
  // Don't forget the keys!
  return [
    <li key="A">First item</li>,
    <li key="B">Second item</li>
  ]

Fragments

render () 
  return (
    <Fragment>
      <li>First item</li>
      <li>Second item</li>
    </Fragment>
  )

See: Fragments and strings

Returning strings

render() 
  return 'Look ma, no spans!';

You can return just a string.

See: Fragments and strings

Errors

class MyComponent extends Component 
  ···
  componentDidCatch (error, info) 
    this.setState( error )
  

Catch errors via componentDidCatch. (React 16+)

See: Error handling in React 16

Portals

render () 
  return React.createPortal(
    this.props.children,
    document.getElementById('menu')
  )

This renders this.props.children into any location in the DOM.

See: Portals

Hydration

const el = document.getElementById('app')
ReactDOM.hydrate(<App />, el)

Use ReactDOM.hydrate instead of using ReactDOM.render if you’re rendering over the output of ReactDOMServer.

See: Hydrate

Property validation

PropTypes

import PropTypes from 'prop-types'

See: Typechecking with PropTypes

KeyDescription
anySomething

Primary

KeyDescription
string
quantity
funcOperate
boolTrue or false

Enum

KeyDescription
oneOf(any)Enum sorts
oneOfType(kind array)Union

Array

KeyDescription
array
arrayOf(…)

Object

KeyDescription
object
objectOf(…)Object with values of a sure kind
instanceOf(…)Occasion of a category
form(…)

Components

KeyDescription
ingredientReact ingredient
nodeDOM node

Required

KeyDescription
(···).isRequiredRequired

Primary sorts

MyComponent.propTypes = 
  e-mail:      PropTypes.string,
  seats:      PropTypes.quantity,
  callback:   PropTypes.func,
  isClosed:   PropTypes.bool,
  any:        PropTypes.any

Required sorts

MyCo.propTypes = 
  identify:  PropTypes.string.isRequired

Components

MyCo.propTypes = 
  // React ingredient
  ingredient: PropTypes.ingredient,

  // num, string, ingredient, or an array of these
  node: PropTypes.node

Enumerables (oneOf)

MyCo.propTypes = 
  path: PropTypes.oneOf([
    'left', 'right'
  ])

Arrays and objects

MyCo.propTypes = 
  checklist: PropTypes.array,
  ages: PropTypes.arrayOf(PropTypes.quantity),
  person: PropTypes.object,
  person: PropTypes.objectOf(PropTypes.quantity),
  message: PropTypes.instanceOf(Message)
MyCo.propTypes = 
  person: PropTypes.form(
    identify: PropTypes.string,
    age:  PropTypes.quantity
  )

Use .array[Of].object[Of].instanceOf.form.

Customized validation

MyCo.propTypes = 
  customProp: (props, key, componentName) => 
    if (!/matchme/.take a look at(props[key])) 
      return new Error('Validation failed!')
    
  

Wrapping Up

And that’s it for this React JS Cheat Sheet for rookies masking React fundamentals. Ofcourse, it’s simply concise article, so it can not cowl each single facet of React. However, I hope it has been an important overview to assist anybody embark on a React journey with out feeling intimidated or too overwhelmed.

Thanks for studying and if you happen to discover this React JS cheat sheet useful, please like and share this text round for extra attain. Cheers!

#React #Cheat #Sheet #Resolve

RELATED ARTICLES
Continue to the category

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -spot_img

Most Popular

Recent Comments