The Ultimate React Cheat Sheet

The Ultimate React Cheat Sheet

Written by Sunil Joshi on Oct 19th, 2020 Views Report Post

React is an open-source, front-end, JavaScript library for building user interfaces or UI components. Just like Vuejs, It gives us the ability to create components, layouts etc in our application. In this article we will go through all the fundamentals of Reactjs in this React Cheat Sheet.

Installation

Using React in our application is quite easy as we can add it using the CDN or by using the CLI to install it from npm.

To add React using the CDN, add this script tags in your html

<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>

Or you can install it using NPM:

npm install react react-dom --save

The --save flag will add react and react-dom into our application depenency.

Using create-react-app

Create React App is a tool that gives you a massive head start when building React apps. It gives us the ability to scaffold a new react project with no configuration. We can install this globally on our local machine by running this command on our terminal:

npm install -g create-react-app

The -g command will install it globally on our local machine.

With this installed, we can now scaffold a react project using this command:

create-react-app <name of project>

When the setup is completed, we can now move into the project and then download the projects dependencies

cd <name of project>
npm install --save

After install, to server your application, run npm start on your terminal.

React DOM

To setup a simple react DOM, we can import ReactDOM, this is what we will use for rendering.

import React from "react";
import ReactDOM from "react-dom";

//define a template
const warning = <h1>Hello,I'm Sunil</h1>;

// ReactDOM.render(root node, mounting point)
ReactDOM.render(warning, document.getElementById("root"));
  • The ReactDOM.render() function takes two arguments, HTML code and an HTML element where the code will be mounted.

Functional Component

This is otherwise known as a stateless component which is is just a plain javascript function which takes props as an argument and returns a react element:

import React from 'react';

const Button = () =>
    <button> Apply</button>

export default Button;

Now to use this component, we can do this:

import React from 'react';

const Button = ({ onClick, className = 'button', children  }) =>
    <button
        onClick={ onClick }
        className={ className }
        type='button'
    >
        { children }
    </button>

export default Button;

Class Component

A Class component acts like a function that receives props, but that function also considers a private internal state as additional input that controls the returned JSX.

import React, { Component } from 'react';

class MyComponent extends Component {
    render() {
        return (
            <div className="main">
                <h1>Helo Devas</h1>
            </div>
        );
    }
}

export default MyComponent;

We can pass in some states:

import React, { Component } from 'react';

class MyComponent () extends Compnent {
    constructor ( props ) {
    super(props);
    this.state = { message: 'Helo Devas' }
    };

    render() {
        return (
            <div className="main">
                <h1>{ this.state.message }</h1>
            </div>
        );
    }
}

export default MyComponent;

Lifecycle Hooks

React component passes through 3 phases which are Mounting, Updating and Unmounting. When a component is about to be mounted, React calls 4 built-in methods:

  • Constructor()
  • getDerivedStateFromProps()
  • render()
  • ComponentDidMount()

Mounting Phases

  • Constructor()

This method is called before anything else in the component, when the component is initiated, and it is the natural place to set up the initial state and other initial values. This method passes a prop as a parameter and always start by calling super(prop) before setting any state or anything else.

class Footer extends React.Component {
constructor(props) {
    super(props);
    this.state = {name: "Sunil"};
  }
  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}

ReactDOM.render(<Footer />, document.getElementById('root'));
  • getDerivedStateFromProps()

This method gets called before rendering elements in the DOM. It is invoked after a component is instantiated as well as when it receives new props.

class Footer extends React.Component {
constructor(props) {
    super(props);
    this.state = {name: "Sunil"};
  }
static getDerivedStateFromProps(props, state) {
    return {name: props.favcol };
  }

  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}

ReactDOM.render(<Footer />, document.getElementById('root'));
  • Render()

This method outputs the defined HTML into the DOM. This is a required method.

class Footer extends React.Component {
  render() {
    return (
      <h1>This template will be rendered using the render function</h1>
    );
  }
}

ReactDOM.render(<Footer />, document.getElementById('root'));
  • ComponentDidMount()

This method gets called immediately after the component is rendered. This is the best place to write statements that requires that the component is already placed in the DOM.

class Footer extends React.Component {
constructor(props) {
    super(props);
    this.state = {name: "Sunil"};
  }

  componentDidMount() {
    // Everything here runs after the component has been mounted
  }
  render() {
    return (
      <h1>My name is {this.state.name}</h1>
    );
  }
}

ReactDOM.render(<Footer />, document.getElementById('root'));

Updating Phase

The component updates whenever there is a change in the component state or props. Some react built-in method gets called when the component is in this state.

  • getDerivedStateFromProps:This method gets called immediately a component is updated. This basically does the same thing as the method in the mounting phase.
  • ShouldComponentUpdate: This method returns a boolean(True or False) which specifies whether React should continue with the rendering or not.
shouldComponentUpdate() {
        return true;
    }
  • render:This method gets called when the component is updated. It re-renders the HTML to the DOM with the new values:
    render() {
        return (
          <h1>This is component is changed</h1>
        );
      }
    }
    
    ReactDOM.render(<Footer />, document.getElementById('root'));
  • getSnapshotBeforeUpdate: This method gives you the ability to have access to the props and state before the component is updated.
    getSnapshotBeforeUpdate(prevProps, prevState) {
        // get acces to the prepious state here
      }
  • ComponentDidUpdate: This method gets called after the component has been updated.
    componentDidUpdate() {
        // do something gere.
       // log the presents state of the component
      }

Unmounting Phase

This is a state where react removes a component from the DOM. This phase comes with a componentWillUnmount built-in method. The method gets called when the component is about to be removed:

componentWillUnmount() {
    alert("Component has been removed");
  }

Props

Props is a concept used in passing data from one component to another. basically it is used for data communication:

import React, { Component } from 'react';

class App extends Component {
    render() {
        return (
            <div className="app">
                <p>My App {this.props.name}</p>
            </div>
        );
    }
}

//passing the data into the component
class Index extends Component {
    render() {
        return (
            <div className="app">
                <App name="Sunil"/>
            </div>
        );
    }
}

export default Index;

React Map

We can iterate through items using the map method. Just like you could use it in Vanilla js, we can have an array of items and then use the map method:

let test = [1,2,3,4,5,6];
const numberList = test.map(number=>console.log(number))

We can also use it in our react component like this:

function App() {
  const people = ['Wisdom', 'Ekpot', 'Sunil','Nirav'];

  return (
    <ul>
      {people.map(person => <Person key={person} name={person} />)}
    </ul>
  );
}

Here we are passing it as an array to the component.

Events

Just like any other framework or library, we have the ability to bind event listeners to our template, this events listen to methods defined. In React, we could define a click event like this:

function App() {

function logSomething() {
    console.log(`Hello i'm sunil`)
  }

return (
    <div>
      <button onClick={logSomething}>Submit</button>
    </div>
  );
}

We can also use the change event listeners too on input fields:

function App() {

function detectChange() {
    console.log(`Changing`)
  }

return (
    <div>
      <input type="text" name="myInput" onChange={detectChange} />
    </div>
  );
}

State

State is basically storing of data. We can store objects, arrays, strings and then use them in our react components. To use the data stored in the state, we can use the this keyword

import React, { Component } from 'react';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {messages: 0};
    } 

    render() {
        return (
            <div className="app">
                <p>My messages: {this.state.messages}</p>
            </div>
        );
    }
}

export default App;

React HMR

The hot module reload retains the application state which is lost during a full reload. It saves compilation time as it only updates what was changed and not the entire application:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import MyComponent from './MyComponent';

ReactDOM.render( <MyComponent />, document.getElementById('root') );

if (module.hot) {
    module.hot.accept();
}

React Router

To handling routing in react, we have to install the react router using NPM:

npm i --save react-router-dom

To route to a component, we can use the <Route /> tag which takes the path and the component we routing to as an attribute:

import { 
  BrowserRouter, 
  Route 
} from 'react-router-dom'

const Hello = () => <h1>Hello world!</h1>

const App = () => (
  <BrowserRouter>
    <div>
      <Route path="/hello" component={Hello} />
    </div>
  </BrowserRouter>
)

React State Hooks

This is basically a state management system. To use this, we have to import useState from react. lets write a simple method which will increment the value of a state when a button is clicked:

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>
  );
}

React Templates

Well as above mentioned thins of react cheat sheet will help you creating your project quicker, there is other option also available, which can save your time. Reactjs Templates are always best to learn as well as to use in your react project to make it complete faster. It gives you many ready to use and well designed components, which will increase your speed of creating project. Do checkout WrapPixel for best react templates.

This article is originally posted at WrapPixel - https://www.wrappixel.com/react-cheat-sheet/

Comments (0)