DEV Community

Cover image for React.js cheatsheet for beginners
Vishnu Sivan
Vishnu Sivan

Posted on

React.js cheatsheet for beginners

React is a JavaScript library developed by Meta for building user interface efficiently with minimal coding. The main objective of React.js is to provide the best possible rendering performance by breaking down the pages into smaller UI components.

The main feature of React.js is the easiness of code writing. We can embed JavaScript codes inside HTML codes using JSX syntax unlike technologies such as Angular where we have to write more lines of code.

In this article, we will learn the basics of React.js.

Getting Started

React Environment Setup

Prerequisites for creating react apps: Node.js and NPM

Sample app creation commands,

npx create-react-app hello-world
cd hello-world
npm start
Enter fullscreen mode Exit fullscreen mode

Components

Components are independent and reusable bits of code. It is similar to JavaScript functions which returns HTML via a render() function. Components are broadly classified into two - Class components and Function components.

Class component

import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
  render() {
    return(
      <div>
         Hello World
      </div>
    )
  }
}
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Function component

import React from 'react'
import ReactDOM from 'react-dom'
function App() {
  return (
    <div>
       Hello World
    </div>
  )
}
ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

State

The state is an instance of React Component Class that can be used to store property values which belongs to the component. The component re-renders when a change in state occurs.

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: "codemaker"
      })
  }
  render() {
    return(
      <div>
        Hello {this.state.name} {/* Using state values */}
      </div>
    )
  }
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Props

Props (Properties) are read-only immutable components. It is an object which stores the value of attributes and serves as a medium to pass data from one component to another. It passes values to the component in the same way as an argument is passed to a function.

import React from 'react'
import ReactDOM from 'react-dom'
class App extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div>
        Hello {this.props.name} {/* Using prop values */}
      </div>
    )
  }
}
ReactDOM.render(
  <React.StrictMode>
    <App name={"codemaker"} /> {/* Provide prop values  */}
  </React.StrictMode>,
  document.getElementById('root')
);
Enter fullscreen mode Exit fullscreen mode

Setting default props/state

The defaultProps is used to set default values for the props. It can be defined as a component property to set the default props for the class. It also provides default values for the state in the constructor.

default props

import React from 'react'
class App extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div>
        Hello {this.props.name} {/* Using prop values */}
      </div>
    )
  }
}
App.defaultProps = {  //Setting default props with values
  name: "codemaker"
}
export default App;
Enter fullscreen mode Exit fullscreen mode

default state

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

Life cycle methods

React is used to call multiple life cycle methods during the component execution of each stage. The method called when the component is created is called mounting. Each component update is called updating. The removal of components is called unmounting. The entire process is called the ‘Component Lifecycle’.

  • Mounting lifecycle methods constructor() static getDerivedStateFromProps() render() componentDidMount()
  • Updating lifecycle methods static getDerivedStateFromProps() shouldComponentUpdate() render() getSnapshotBeforeUpdate() componentDidUpdate()
  • Unmounting lifecycle method componentWillUnmount
  • Error handling lifecycle methods static getDerivedStateFromError() componentDidCatch()

Life cycle methods
Image credits projects.wojtekmaj.pl

Life cycle methods

DOM references

React uses refs for DOM access in the component. It can be achieved by adding a ref attribute to an element in your application.

import React from 'react';
class App extends Component {
  render () {
    return <div>
      <input ref={el => this.input = el} />
    </div>
  }  componentDidMount () {
    this.input.focus()
  }
}
export default App;
Enter fullscreen mode Exit fullscreen mode

DOM events

Event is an action that could be triggered as a result of the user action or a system-generated action. React has its own event handling system known as Synthetic Events which is very similar to the event handling on DOM elements.

React events has some syntactic differences from the DOM events. They are:

  • React events are named in the camelCase format instead of the lowercase format.
  • React event handler requires a function instead of a string.
import React from 'react';
class App extends Component {
  render () {
     return (
        <input type="text"
           value={this.state.value}
           onChange={event => this.onChange(event)} />
     )
  }
  onChange (event) {
    this.setState({ value: event.target.value })
  }
}
export default App;
Enter fullscreen mode Exit fullscreen mode

JSX (Javascript XML)

JSX enables users to write JavaScript in HTML. It writes HTML elements in JavaScript and places them in the DOM without any createElement() or appendChild() methods.

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
         <div>
            <p>Hello World</p>
            <p>{8+5}</p> {/* JSX expression */}
            <p className={"demo-class"}>class name test</p> {/* Accessing css class */}
            <div style={{backgroundColor: 'red'}}> style option test</div>  {/* Defining styles inside component */}
            <h1>{i == 1 ? 'True' : 'False'}</h1> {/* Conditional statements */}
            {i == 1 ? <div>Hello</div> : <div>Haii</div>} {/* Conditional rendering */}
            {i == 1 && <div>Test</div>} {/* Short evaluation */}
            {items.map(item =>          //List rendering in JSX
                         <p>{item}</p>  
                      )
            }
            {//End of the line Comment...}
            {/*Multi line comment...*/}
         </div>
      );
   }
}
export default App;
Enter fullscreen mode Exit fullscreen mode

Conditional rendering

React offers conditional rendering to render a particular component or code snippet based on some condition or the state of our application.

import React from 'react';   
import ReactDOM from 'react-dom';
class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isAuthenticated: true,
    }
 }
  render() {  
    const isAuthenticated = this.state.isAuthenticated;  
    return (  
       <div>  
         Welcome {isAuthenticated ? 'Authenticated User' : 'Please login to continue'}.  
       </div>  
    );  
  }  
}
Enter fullscreen mode Exit fullscreen mode

Property validation

Props validation is a mechanism used to avoid props data-related issues. The PropTypes is a react component property which enables users to validate data types of values passed through props.

import React from 'react';  
import PropTypes from 'prop-types';
class App extends React.Component {  
   render() {  
        return (  
            <div>  
                <p>{this.props.propArray}</p>  
                <p>{this.props.propBool}</p>  
                <p>{this.props.propFunc(5)}</p>  
                <p>{this.props.propString}</p>  
                <p>{this.props.propNumber}</p>  
            </div>  
        );  
   }  
}  
App.propTypes = {  
    propArray: PropTypes.array.isRequired,  
    propBool: PropTypes.bool.isRequired,  
    propFunc: PropTypes.func,  
    propNumber: PropTypes.number,  
    propString: PropTypes.string,   
}  
App.defaultProps = {  
    propArray: [1,2,3],  
    propBool: true,  
    propFunc: function(x){return x+3},  
    propNumber: 1,  
    propString: "codemaker",  
}  
export default App;
Enter fullscreen mode Exit fullscreen mode

React Router

React Router is a JavaScript library used to create routing in the React application. Routing is a mechanism where we can navigate to different pages when the URL path matches any ‘route’ inside the router file.

Installation

npm install react-router-dom --save
Enter fullscreen mode Exit fullscreen mode

There are two types of router components:

  • BrowserRouter: It is used for handling dynamic URLs.
  • HashRouter: It is used for handling static requests.

Example

// This is a React Router v6 app
import { BrowserRouter, Routes, Route } from "react-router-dom";
function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="users/*" element={<Users />} />
      </Routes>
    </BrowserRouter>
  );
}
Enter fullscreen mode Exit fullscreen mode

React Hooks

Hooks were introduced in React 16.8. It enables users to use props and states directly inside a function component. It is useful to manage the component state and perform an after-effect when certain changes occur in the state without writing a class.

Hooks are similar to JavaScript functions, but it is essential you follow these rules while using them.

  • Only call Hooks at the top level: Hooks should always be used at the top level of the React functions and it is necessary not to call them inside loops, conditions, or nested functions.
  • Only call Hooks from React functions: Call Hook only from function components and custom Hooks.
import React, { useState, useEffect } from 'react';  

function App() {
  // Declare a new state variable, which we'll call "count"
  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`;  
  });  

  return (  
    <div>  
      <p>You clicked {count} times</p>  {/* Access state values */}
      <button onClick={() => setCount(count + 1)}>  {/* Updating state values using setCount */}
        Click me  
      </button>  
    </div>  
  );  
}  
export default App;
Enter fullscreen mode Exit fullscreen mode

The built-in Hooks are divided into two — Basic hooks and additional hooks.

Basic Hooks

  • useState
  • useEffect
  • useContext

Additional Hooks

  • useReducer
  • useCallback
  • useMemo
  • useRef
  • useImperativeHandle
  • useLayoutEffect
  • useDebugValue

React context

Context enables users to pass data to the child components without passing props down manually at each level.

// Create a context for the user authentication.  
const AuthContext = React.createContext('auth');  

class App extends React.Component {  
 render() {  
      /* Use a ContextProvider to pass the auth information, 
         we are passing the "true" as the current value.*/  
      return (  
         <AuthContext.Provider value="true">  
           <App />  
         </AuthContext.Provider>  
      );  
   }  
}  

// Now, it is not required to pass the auth down explicitly for every component.  
function App(props) {  
   return (  
      <Home /> 
   );  
}  

class Home extends React.Component {  
 static contextType = AuthContext;  
   render() {  
      return <Button auth={this.context} />;  
   }  
}
Enter fullscreen mode Exit fullscreen mode

Reactstrap

Reactstrap is a javascript library that provides inbuilt Bootstrap components that makes it easier to create UI for your application with inbuilt validations. Reactstrap now supports Bootstrap 5.1.

Installation:

npm install reactstrap react react-dom
npm install --save bootstrap
Enter fullscreen mode Exit fullscreen mode

Example:

import React from 'react';
import { Button } from 'reactstrap';
import 'bootstrap/dist/css/bootstrap.min.css';
function App() {
  return (
    <Button color="danger">Cancel</Button>
  );
};
Enter fullscreen mode Exit fullscreen mode

Error Boundaries

React 16 introduces a new approach in handling errors within your application by using error boundaries. It allows the user to keep the app running in spite of an error occurring during the runtime and displays a fallback UI to the user.

import React from 'react';
class ErrorBoundary extends React.Component {  
   constructor(props) {  
      super(props);  
      this.state = { hasError: false };  
   }  
   static getDerivedStateFromError(error) {  
      // It will update the state so the next render 
      // and shows the fallback UI.  
      return { hasError: true };  
   }  
   componentDidCatch(error, info) {  
      // It will catch error in any component below. 
      // We can also log the error to an error reporting service.  
      logErrorToMyService(error, info);  
   }  
   render() {  
      if (this.state.hasError) {  
          return (  
           <div>Oops! Error occurs.</div>;  
       );  
      }  
      return this.props.children;   
   }  
}
// Wrap the error boundary around your component
<ErrorBoundary>  
 <App/>  
</ErrorBoundary>
Enter fullscreen mode Exit fullscreen mode

React.js vs React native

React.js is an open-source JavaScript library used to build the user interface for Web Applications whereas React Native is used for developing a mobile application for iOS and Android. React Native is almost similar to React, however, it uses native components instead of web components as building blocks and targets mobile platforms over browsers.

React.js vs React native
Image credits Javapoint

Summary

Summary

Thanks for reading this article.

Thanks Gowri M Bhatt for reviewing the content.

To get the article in pdf format: React.js-cheatsheet.pdf

The article is also available on Medium

If you enjoyed this article, please click on the heart button ♥ and share to help others find it!

If you are interested in further exploring, here are some resources I found helpful along the way:

Top comments (0)