Open In App

React Cheat Sheet

Last Updated : 17 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

React is an open-source JavaScript library used to create user interfaces in a declarative and efficient way. It is a component-based front-end library responsible only for the view layer of a Model View Controller (MVC) architecture. React is used to create modular user interfaces and promotes the development of reusable UI components that display dynamic data.

react-cheat-sheet

React Cheat Sheet

The react cheat sheet provides you simple and quick references to commonly used react methods. This single page contains all the important concepts and features of react required for performing all the basic tasks in React. It’s a great resource for both beginners and experienced developers to quickly look up React essentials.

Basic Setup

Follow the below steps to create a boilerplate

Step 1: Create the application using the command

npx create-react-app <<Project_Name>>

Step 2: Navigate to the folder using the command

cd <<Project_Name>>

Step 3: Open the App.js file and write the below code

// App.js

import React from 'react';
import './App.css';
export default function App() {
    return (
        <div >
            Hello Geeks
            Lets start learning React
        </div>
    )
}

JSX

JSX stands for JavaScript XML. JSX is basically a syntax extension of JavaScript. It helps us to write HTML in JavaScript and forms the basis of React Development. Using JSX is not compulsory but it is highly recommended for programming in React as it makes the development process easier as the code becomes easy to write and read. 

Sample JSX code:

const ele = <h1>This is sample JSX</h1>;

React Elements

React elements are different from DOM elements as React elements are simple JavaScript objects and are efficient to create. React elements are the building blocks of any React app and should not be confused with React components.

React ElementDescriptionSyntax
Class Element AttributesPasses attributes to an element. The major change is that class is changed to className<div className= “exampleclass”></div>
Style Element AttributesAdds custom styling. We have to pass values in double parenthesis like {{}}<div style= {{styleName: Value}}</div>
FragmentsUsed to create single parent component<>//Other Components</>

ReactJS Import and Export

In ReactJS we use importing and exporting to import already created modules and export our own components and modules rescpectively

Type of Import/ExportDescriptionSyntax
Importing Default exportsimports the default export from modulesimport MOD_NAME from “PATH”
Importing Named Valuesimports the named export from modulesimport {NAME} from “PATH”
Multiple importsUsed to import multiple modules can be user defined of npm packagesimport MOD_NAME, {NAME} from “PATH”
Default ExportsCreates one default export. Each component can have onne default exportexport default MOD_NAME
Named ExportsCreates Named Exports when there are multiple components in a single moduleexport default {NAME}
Multiple ExportsExports mulitple named components export default {NAME1, NAME2}

React Components

A Component is one of the core building blocks of React. Components in React basically return a piece of JSX code that tells what should be rendered on the screen.

ComponentDescriptionSyntax
FunctionalSimple JS functions and are statelessfunction demoComponent() {
   return (<>
               // CODE
           </>);
}
Class-basedUses JS classes to create stateful componentsclass Democomponent extends React.Component {
   render() {
       return <>//CODE</>;
   }
}
NestedCreates component inside another componentfunction demoComponent() {
   return (<>
               <Another_Component/>
           </>);
}
// Functional Component

export default function App() {
    return (
        <div >
            Hello Geeks
            Lets start learning React
        </div>
    )
}

// Class Component with nesting
class Example extends React.Component {
  render() {
    return (
          <div >
              <App/>
            Hello Geeks
            Lets start learning React
        </div>
     )
  }
}

Managing Data Inside and Outside Components(State and props)

PropertyDescriptionSyntax
propsPasses data between components and is read-only. Mainly used in functional components

// Passing
<Comp prop_name=”VAL”/>

//Accessing
<Comp>{this.props.prop_name}</Comp>

stateManages data inside a component and is mutable. Used with class componentsconstructor(props) {
       super(props);
       this.state = {
           var: value,
       };
 }
setStateUpdates the value of a state using callback function. it is an asynchronous function callthis.setState((prevState)=>({
          // CODE LOGIC
 }))
const App = () => {
  const message = "Hello from functional component!";

  return (
    <div>
      <ClassComponent message={message} />
    </div>
  );
};

class ClassComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: this.props.message
    };
  }

  render() {
    return (
      <div>
        <h2>Class Component</h2>
        <p>State from prop: {this.state.message}</p>
      </div>
    );
  }
}

Lifecycle of Components

The lifecycle methods in ReactJS are used to control the components at different stages from initialization till unmounting.

Mounting Phase methods

MethodDescriptionSyntax
constructorRuns before component renderingconstructor(props){}
renderUsed to render the componentrender()
componentDidMountRuns after component is renderedcomponentDidMount()
componentWillUnmountRuns before a component is removed from DOMcomoponentWillUnmount()
componentDidCatchUsed to catch errors in componentcomponentDidCatch()

Updating Phase Methods

MethodDescriptionSyntax
componentDidUpdateInvokes after component is updatedcomponentDidUpdate(prevProp, prevState, snap)
shouldComponentUpdateUsed to avoid call in while re-renderingshouldComponentUpdate(newProp. newState)
renderRender component after updaterender()
import React from 'react';
import ReactDOM from 'react-dom';

class Test extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hello: "World!" };
    }

    componentWillMount() {
        console.log("componentWillMount()");
    }

    componentDidMount() {
        console.log("componentDidMount()");
    }

    changeState() {
        this.setState({ hello: "Geek!" });
    }

    render() {
        return (
            <div>
                <h1>GeeksForGeeks.org, Hello{this.state.hello}</h1>
                <h2>
                    <a onClick={this.changeState.bind(this)}>Press Here!</a>
                </h2>
            </div>);
    }

    shouldComponentUpdate(nextProps, nextState) {
        console.log("shouldComponentUpdate()");
        return true;
    }

    componentWillUpdate() {
        console.log("componentWillUpdate()");
    }

    componentDidUpdate() {
        console.log("componentDidUpdate()");
    }
}

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

Conditional Rendering

In React, conditional rendering is used to render components based on some conditions. If the condition is satisfied then only the component will be rendered. This helps in encapsulation as the user is allowed to see only the desired component and nothing else.

TypeDescriptionSyntax
if-elseComponent is rendered using if-else blockif (condition) {
    return <COMP1 />;
}else{
    return <COMP2/>;
}
Logical && OperatorUsed for showing/hiding single component based on condition{condition && <Component/>}
Ternary OperatorComponent is rendered using if-else block{Condition
       ? <COMP1/>
       : <COMP2/>
 }
JavaScript
// Conditional Rendering Using if-else

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

// Example Component
function Example(props)
{
    if(!props.toDisplay)
        return null;
    else
        return <h1>Component is rendered</h1>;
}

ReactDOM.render(
    <div>
        <Example toDisplay = {true} />
        <Example toDisplay = {false} />
    </div>,
    document.getElementById('root')
);
JavaScript JavaScript

React Lists

We can create lists in React in a similar manner as we do in regular JavaScript i.e. by storing the list in an array. In order to traverse a list we will use the map() function.

Keys are used in React to identify which items in the list are changed, updated, or deleted. Keys are used to give an identity to the elements in the lists. It is recommended to use a string as a key that uniquely identifies the items in the list.

Code Snippet:

const arr = [];
const listItems = numbers.map((number) =>
  <li key={number.toString()}>
    {number}
  </li>
);
import React from 'react';
import ReactDOM from 'react-dom';

const numbers = [1,2,3,4,5];

const updatedNums = numbers.map((number)=>{
    return <li>{number}</li>;
});

ReactDOM.render(
    <ul>
        {updatedNums}
    </ul>,
    document.getElementById('root')
);

React DOM Events

Similar to HTML events, React DOM events are used to perform events based on user inputs such as click, onChange, mouseOver etc

MethodDescriptionSyntax
ClickTriggers an event on click<button onClick={func}>CONTENT</button>
ChangeTriggers when some change is detected in component <input onChange={handleChange} />
SubmitTriggers an event when form is submitted<form onSubmit={(e) => {//LOGIC}}></form>
import React, { useState } from "react";

const App = () => {
// Counter is a state initialized to 0
const [counter, setCounter] = useState(0)

// Function is called everytime increment button is clicked
const handleClick1 = () => {
    // Counter state is incremented
    setCounter(counter + 1)
}

// Function is called everytime decrement button is clicked
const handleClick2 = () => {
    // Counter state is decremented
    setCounter(counter - 1)
}

return (
    <div>
    Counter App
        <div style={{
            fontSize: '120%',
            position: 'relative',
            top: '10vh',
        }}>
            {counter}
        </div>
        <div className="buttons">
            <button onClick={handleClick1}>Increment</button>
            <button onClick={handleClick2}>Decrement</button>
        </div>
    </div>
)
}

export default App

React Hooks

Hooks are used to give functional components an access to use the states and are used to manage side-effects in React. They were introduced React 16.8. They let developers use state and other React features without writing a class For example- State of a component It is important to note that hooks are not used inside the classes.

HookDescriptionSyntax
useStateDeclares state variable inside a functionconst [var, setVar] = useState(Val);
useEffectHandle side effect in ReactuseEffect(<FUNCTION>, <DEPENDECY>)
useRefDirectly creates reference to DOM elementconst refContainer = useRef(initialValue);
useMemoReturns a memoized valueconst memVal = useMemo(function, 
 arrayDependencies)
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
function App() {
    const [click, setClick] = useState(0);
    // using array destructuring here
    // to assign initial value 0
    // to click and a reference to the function
    // that updates click to setClick
    return (
        <div>
            <p>You clicked {click} times</p>

            <button onClick={() => setClick(click + 1)}>
                Click me
            </button>
        </div>
    );
}

export default App;

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
    <App />
</React.StrictMode>
);

PropTypes

PropTypes in React are used to check the value of a prop which is passed into the component. These help in error hanling and are very useful in large scale applications.

Primitive Data Types 

TypeClass/SyntaxExample
StringPropTypes.string“Geeks”
ObjectPropType.object{course: “DSA”}
NumberPropType.number15,
BooleanPropType.booltrue
FunctionPropType.funcconst GFG ={return “Hello”}
SymbolPropType.symbolSymbol(“symbole_here”

Array Types

TypeClass/SyntaxExample
ArrayPropTypes.array[]
Array of stringsPropTypes.arrayOf([type])[15,16,17]
Array of numbersPropTypes.oneOf([arr])[“Geeks”, “For”, “Geeks”
Array of objectsPropTypes.oneOfType([types])PropTypes.instanceOf()

Object Types

TypeClass/SyntaxExample
ObjectPropTypes.object(){course: “DSA”}
Number ObjectPropTypes.objectOf(){id: 25}
Object ShapePropTypes.shape()

{course: PropTypes.string,
price: PropTypes.number}

InstancePropTypes.objectOf()new obj()
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom/client';

// Component
class ComponentExample extends React.Component{
    render(){
        return(
                <div>
                
                    {/* printing all props */}
                    <h1>
                        {this.props.arrayProp}
                        <br />

                        {this.props.stringProp}
                        <br />

                        {this.props.numberProp}
                        <br />

                        {this.props.boolProp}
                        <br />
                    </h1>
                </div>
            );
    }
}

// Validating prop types
ComponentExample.propTypes = {
    arrayProp: PropTypes.array,
    stringProp: PropTypes.string,
    numberProp: PropTypes.number,
    boolProp: PropTypes.bool,
}

// Creating default props
ComponentExample.defaultProps = {

    arrayProp: ['Ram', 'Shyam', 'Raghav'],
    stringProp: "GeeksforGeeks",
    numberProp: "10",
    boolProp: true,
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
    <ComponentExample />
</React.StrictMode>
);

Error Boundaries

Error Boundaries basically provide some sort of boundaries or checks on errors, They are React components that are used to handle JavaScript errors in their child component tree.

React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI. It catches errors during rendering, in lifecycle methods, etc.

import React, { Component } from 'react';

class ErrorBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false };
    }

    componentDidCatch(error, info) {
        // Log the error to an error reporting service
        console.error('Error:', error);
        console.error('Info:', info);
        this.setState({ hasError: true });
    }

    render() {
        if (this.state.hasError) {
            // Fallback UI when an error occurs
            return <div>Something went wrong!</div>;
        }
        return this.props.children;
    }
}

export default ErrorBoundary;

//Apply Error Boundary

import React from 'react';
import ErrorBoundary from './ErrorBoundary';

function App() {
    return (
        <ErrorBoundary>
            <div>
                {/* Your components here */}
            </div>
        </ErrorBoundary>
    );
}

export default App;

This React Cheat Sheet gives you quick access to the most commonly used React concepts and methods. From setting up project to managing state and handling events, everything to build dynamic and responsive user interfaces with React.



Next Article

Similar Reads

three90RightbarBannerImg