React Cheat Sheet

Tuesday, March 29, 2022

React is one of the most popular front-end JS libraries that can be used by software engineers to create user interfaces as per UI components, most of the newbies want to learn it and make it their career. And to make it easier for every React developer, be it a fresher or an expert, here we will go through various React cheat sheet techniques that help them learn every important concept of this technology.

1. What is React?

React is a very popular, declarative, efficient, and flexible JavaScript library. It is used by app developers to create user interfaces. It is a ‘V’ (View) in Model View Controller (MVC). ReactJS is a component-based open-source front-end app development library that is responsible only for the application’s view layer. React is created and maintained by Facebook.

This technology utilizes a declarative paradigm that makes it very simple and easy to reason about the application and its aim to be flexible and efficient. By following React js best practices you can design simple views for every stage of the app and it efficiently renders and updates the perfect component when the data in the app changes. This means that the declarative view is able to make the code predictable and this makes it easier to debug than ever.

2. Top React Cheat Sheet

Some of the most popular approaches to React cheat sheet are –

2.1 App Components

Components in React are known as the building blocks for an application. They are functions that are capable of returning an HTML element. Basically, one can say that an app component in React is just like a big HTML block of code that has the capability to independently do a certain type of functionality for the React application. Just like the panels or the navigation bar.

In the React app, the components are structured in such a manner that it looks like a node in the Virtual DOM. These React components will render onto the web browser. And the rendering will be as per the ways we specify them to look like. There are two essential types of React components currently in the market and they are Function component & Class component.

Function Components

Function or functional component is a popular type of React component that enables the developers to return HTML codes. The names in these components must start with capital letters. To understand this in a better way, let us go through an example where we will create Car and Color as functional components in a function app.

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

function Car() {
  return (
    

This is my car

); } function Color() { return (

White

); }
ReactDOM.render(, document.getElementById("root"));

This is it. The components work the same way and render the same elements of HTML. But in this, one thing that you must remember is that you don’t require the render() function prior to the return statement.

Class Components

The class component is nothing but the classes that are written in the context of React. The only rule for writing the class components is that its name must start with a capital letter. To make the concept more clear for you, let’s have a look at an example. Here we will write a simple class component, named Car. For this, we will first have to import react-dom and react, then write the class Car, and later on, call the function ReactDOM.render().

import React from 'react'
import ReactDOM from 'react-dom'

class Car extends React.Component {
  render() {
    return (
      

This is my car

) } } //3. ReactDOM.render(, document.getElementById('root'));

Now, to take this ahead, we will create class Color and this new class will act as a child component to class Car.

Here we will create a class named Color.

class Color extends React.Component {
  render() {
    return (
      

White

) } }

Now, here we will add the Color class in the Car class. As this makes Color the child class of Car.

class Car extends React.Component {
  render() {
    return (
      

This is my car

) } }

The image below is the outcome that shows what the application will look like in the web browser. Here, both the classes are displayed, and to show that the Color is the child class of Car (parent component class), it is outlined with a red box and is placed inside Car.

2.2 States

The state is nothing but a very simple and plain JavaScript object that can be utilized by the React developers to represent any type of information about the current situation of the React app components. States are managed in the components, just like how any variable of the app is declared in a function. The state is an illustration of React Component Class and it can be easily defined as an object of a set of properties that are observable. These properties are able to control the component’s behavior. Basically, a state is an object that enables the developers to save the property values that are a part of a component. This means that when any state object changes, it will automatically re-render the component.

import React from 'react'
class App extends React.Component {
  constructor(props) {
      super(props);
      this.state = {  //Initializing state values
        name: ""
      }
  }
  componentDidMount() {
      this.setState({  //Updating state values
        name: "tatvasoft"
      })
  }
  render() {
    return(
      
Hello {this.state.name} {/* Using state values */}
) } } export default App;

2.3 Props

Props or properties are also components but they are read-only immutable ones. Basically, a prop is an object that can store the attribute’s value, and these attributes work just like the ones in HTML. This means that props are immutable components that can offer a way to pass information from one component to another. The properties can pass data in a similar way as arguments are passed to a normal function.

import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      
Hello {this.props.name} {/* Using prop values */}
) } } ReactDOM.render( {/* Provide prop values */} , document.getElementById('root') )

2.4 State Hook

A Hook is a very special type of function that enables the developers to hook into the features of React applications. For instance, useState, a Hook that enables the React developer to include a React state to function components. To understand it more clearly, let us go through an example and see how to use  React Hooks to control the states. For this, let’s have a glance at some of the React Hooks and their examples.

useState()

It is a React Hook that enables the function components to start and update states. For instance –

import React, { useState } from "react";
import ReactDOM from "react-dom";

function Car() {
  const [color, setColor] = useState("white");
  return (
    

This is a {color} car

); }

In the above code, we have initialized the state as white inside the Hook, useState. Later, the Hook here returns the value of the state and the function that is set with it to update the state. After that, you can simply add a value of the state in the function that returns and at the end, the application will be able to display the state.

2.5 Effect Hook 

useEffect()

Another useful Hook is the useEffect Hook. This React Hook has the capability to perform a function whenever any particular state changes. If we look at the House component example and add a new variable in it, Door which can help in tracking the number of Doors in the main House component, the useState must be initialized to 0.Later, when a button onClick is initialized, a value is added to increase the value of Door variable by 1. Then, the useEffect Hook will print the total number of doors in the house. And this is done every time the door’s value is updated. You can have a look about it in the below code –

function House() {
  const [color, setColor] = useState("white");
  const [door, setDoor] = useState(0); //initialize door as 0

//add 1 to the current value of door on every button click
  const addDoor = () => {
    setDoor(door + 1);
  };

//finally, trigger the function to print the door value whenever door is updated
  useEffect(() => {
    console.log(`Door Count: ${door}`)
  }, [door]);

  return (
    

This is a {color} Castle house

); }

The result of this code is –

2.6 JSX Element

React apps are organized by utilizing a syntax called JSX. JavaScript XML (JSX) enables the developers to write HTML in React apps. It is utilized to write the elements of HTML in JavaScript and then place these elements in the Virtual DOM without any methods like appendChild() or createElement().

import React from 'react';
class App extends React.Component {
   render() {
      var i = 1;
      const { items } = this.props
      return ( // JSX syntax. Using HTML code in Javascript
         

Hello TatvaSoft

{8+5}

{/* JSX expression */}

class name test

{/* Accessing css class */}
style option test
{/* Defining styles inside component */}

{i == 1 ? 'True' : 'False'}

{/* Conditional statements */} {i == 1 ?
Hello
:
Haii
} {/* Conditional rendering */} {i == 1 &&
Test
} {/* Short evaluation */} {items.map(item => //List rendering in JSX

{item}

) } {//End of the line Comment...} {/*Multi line comment...*/}
); } } export default App;

2.7 CSS Modules

When developers create a React app and they want to style it, they can create a .css file and then import this CSS file to the React Component. Here is a simple styles.css file for your example.

h2 {
  font-family: "Gill Sans", "Gill Sans MT", Calibri, "Trebuchet MS", sans-serif;
  padding: 10px 5px;
  border-radius: 10px;
}

After this, you can import a file in the Car component file, just like shown below.

import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./style.css"; //import here

//keep everything else the same
function Car() {
  const [color, setColor] = useState("red");

  const style = {
    border: `1px solid ${color}`
  };

  return (
    

This is a {color} car

); }

This is the output you will get.

2.8 Children

Children are the props that are used in React to utilize and access what a developer puts inside to the opening and closing tags. And this is when the developer tries to create a sample of a component. React.Children is something that offers various utilities that are useful when the developer has to deal with this.props.children opaque data structure. Some of the popular methods in Reach.Children are –

  • React.Children.map
  • React.Children.forEach
  • React.Children.count
  • React.Children.only
  • React.Children.toArray

3. Conclusion

As you can see in this blog, there are many important factors to learn about React. This is why every developer goes through the React cheat sheet and understands every React context so that he/she can work properly and effectively on their development project.

More Resources on Cheat Sheet:
Node Cheat Sheet 
Angular Cheat Sheet

Comments


Your comment is awaiting moderation.