DEV Community

V Sai Harsha
V Sai Harsha

Posted on • Updated on

React.js Cheatsheet

Introduction

React.js is a popular JavaScript library for building user interfaces. Whether you're a beginner or an experienced developer, this React.js cheatsheet will help you quickly reference key concepts, syntax, and best practices.

Table of Contents

  1. Components
  2. JSX
  3. Props
  4. State
  5. Lifecycle Methods
  6. Events
  7. Hooks
  8. Conditional Rendering
  9. Lists and Keys
  10. Forms and Controlled Components
  11. Context API
  12. Refs
  13. Styling
  14. Error Handling
  15. Conclusion

Components

React applications are built using components, which are reusable, self-contained UI elements. Components can be functional or class-based.

Functional Component:

function MyComponent(props) {
  return <div>Hello, {props.name}</div>;
}
Enter fullscreen mode Exit fullscreen mode

JSX

JSX is a syntax extension for JavaScript used in React to describe the structure of your UI. It allows you to write HTML-like code within JavaScript.

Example:

const element = <h1>Hello, World!</h1>;
Enter fullscreen mode Exit fullscreen mode

Props

Props (short for properties) are inputs to a component. They allow you to pass data from parent components to child components.

Usage:

<MyComponent name="John" />
Enter fullscreen mode Exit fullscreen mode

Accessing props:

function MyComponent(props) {
  return <div>Hello, {props.name}</div>;
}
Enter fullscreen mode Exit fullscreen mode

State

State is used to manage a component's internal data. It can be modified using setState, triggering a re-render.

Example:

import React, { useState } from 'react';

function Counter() {
  // Declare a state variable 'count' and a function to update it 'setCount'
  const [count, setCount] = useState(0);

  // Event handler to increment the count when a button is clicked
  const handleIncrement = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={handleIncrement}>Increment</button>
    </div>
  );
}

export default Counter;

Enter fullscreen mode Exit fullscreen mode

Events

React uses synthetic events, similar to native DOM events. Event handlers are defined using camelCase attributes.

Example:

   function handleClick() {
       console.log("Hi Mom!")
   }

  function MyButton() {
    return <button onClick={() => {handleClick()}>Click Me</button>;
  }

Enter fullscreen mode Exit fullscreen mode

Hooks

Hooks are functions that allow you to use state and other React features in functional components. Common hooks include useState and useEffect.

Example:

import React, { useState, useEffect } from 'react';

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

  useEffect(() => {
    // Perform side effects
  }, [count]);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Conditional Rendering

Conditional rendering allows you to show or hide elements based on conditions.

Example:

function MyComponent(props) {
  return (
    <div>
      {props.isLoggedIn ? <p>Welcome, {props.username}</p> : <p>Please log in</p>}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Lists and Keys

To render lists of items, map over the data and provide a unique key prop to each item.

Example:

function MyListComponent(props) {
  const items = props.data.map((item) => (
    <li key={item.id}>{item.name}</li>
  ));

  return <ul>{items}</ul>;
}
Enter fullscreen mode Exit fullscreen mode

Context API

The Context API provides a way to pass data through the component tree without having to pass props manually at every level.

Example:

const MyContext = React.createContext();

function MyComponent() {
  return (
    <MyContext.Provider value="Hello, Context!">
      <MyChildComponent />
    </MyContext.Provider>
  );
}

function MyChildComponent() {
  const contextValue = React.useContext(MyContext);
  return <div>{contextValue}</div>;
}
Enter fullscreen mode Exit fullscreen mode

Refs

Refs are used to access the DOM or React elements directly. They can be created using useRef hook.

Example:

  import { useRef } from 'react'

  function MyInput() {
  const myRef = useRef(null)
    return <input ref={myRef} />;
  }
}
Enter fullscreen mode Exit fullscreen mode

Styling

You can apply styles to components using CSS classes, inline styles, or CSS-in-JS libraries like styled-components or emotion.

Example (inline styles):

const divStyle = {
  color: 'blue',
  backgroundColor: 'lightgray',
};

function MyComponent() {
  return <div style={divStyle}>Styled Div</div>;
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

This React.js cheatsheet provides a quick reference to essential concepts and features in React development. React is a powerful library for building user interfaces, and understanding these key concepts will help you create dynamic and responsive web applications.

Top comments (3)

Collapse
 
easewithtuts profile image
V Sai Harsha

@zu I have removed code examples which have class components to function components

Collapse
 
zu profile image
zu

why still class

Collapse
 
easewithtuts profile image
V Sai Harsha

Replaced classes with functions