React.js Cheatsheet
Tags: webdev, javascript, react, cheatsheet
Published: 2023-09-07 00:32:59

## 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**](#components)
2. [**JSX**](#jsx)
3. [**Props**](#props)
4. [**State**](#state)
5. [**Lifecycle Methods**](#lifecycle-methods)
6. [**Events**](#events)
7. [**Hooks**](#hooks)
8. [**Conditional Rendering**](#conditional-rendering)
9. [**Lists and Keys**](#lists-and-keys)
10. [**Forms and Controlled Components**](#forms-and-controlled-components)
11. [**Context API**](#context-api)
12. [**Refs**](#refs)
13. [**Styling**](#styling)
14. [**Error Handling**](#error-handling)
15. [**Conclusion**](#conclusion)

---

## Components

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

**Functional Component:**

```jsx
function MyComponent(props) {
  return <div>Hello, {props.name}</div>;
}
```

---

## 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:

```jsx
const element = <h1>Hello, World!</h1>;
```

---

## Props

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

Usage:

```jsx
<MyComponent name="John" />
```

Accessing props:

```jsx
function MyComponent(props) {
  return <div>Hello, {props.name}</div>;
}
```

---

## State

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

Example:

```jsx
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;

```

---


## Events

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

Example:

```jsx
   function handleClick() {
       console.log("Hi Mom!")
   }
  
  function MyButton() {
    return <button onClick={() => {handleClick()}>Click Me</button>;
  }

```

---

## Hooks

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

Example:

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

---

## Conditional Rendering

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

Example:

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

---

## Lists and Keys

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

Example:

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

  return <ul>{items}</ul>;
}
```

---

## 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:

```jsx
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>;
}
```

---

## Refs

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

Example:

```jsx
  import { useRef } from 'react'

  function MyInput() {
  const myRef = useRef(null)
    return <input ref={myRef} />;
  }
}
```

---

## 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):

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

function MyComponent() {
  return <div style={divStyle}>Styled Div</div>;
}
```

---

## 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.