Skip to content

React Cheat Sheet

Updated: at 09:12 AM
  1. Introduction

    • No code here, just explanations and potentially screenshots of the development environment setup.
  2. JavaScript ES6+ Basics

    • Arrow functions:
    const sayHello = name => {
      console.log(`Hello, ${name}!`);
    };
    sayHello("World");
    
  3. React Basics

    • Example of a functional component in JSX:
    import React from "react";
    
    const HelloWorld = () => {
      return <h1>Hello, World!</h1>;
    };
    
    export default HelloWorld;
    
  4. React Component Lifecycle

    • Basic example of lifecycle methods:
    import React from "react";
    
    class LifecycleExample extends React.Component {
      constructor(props) {
        super(props);
        this.state = { favoriteColor: "red" };
      }
    
      componentDidMount() {
        setTimeout(() => {
          this.setState({ favoriteColor: "blue" });
        }, 1000);
      }
    
      componentDidUpdate() {
        // This method is called after the component updates
        document.getElementById("myDiv").innerHTML =
          `The updated favorite color is ${this.state.favoriteColor}`;
      }
    
      render() {
        return (
          <div>
            <h1>My Favorite Color is {this.state.favoriteColor}</h1>
            <div id="myDiv"></div>
          </div>
        );
      }
    }
    
    export default LifecycleExample;
    
  5. React Hooks

    • Using useState and useEffect:
    import React, { useState, useEffect } from "react";
    
    const Counter = () => {
      const [count, setCount] = useState(0);
    
      useEffect(() => {
        document.title = `Count: ${count}`;
      });
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
      );
    };
    
    export default Counter;
    
  6. Advanced Topics

    • Using the Context API:
    import React, { useState, useContext, createContext } from "react";
    
    const CountContext = createContext();
    
    const CountProvider = ({ children }) => {
      const [count, setCount] = useState(0);
    
      return (
        <CountContext.Provider value={{ count, setCount }}>
          {children}
        </CountContext.Provider>
      );
    };
    
    const Counter = () => {
      const { count, setCount } = useContext(CountContext);
    
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
      );
    };
    
    export const App = () => (
      <CountProvider>
        <Counter />
      </CountProvider>
    );
    
  7. Working with Forms in React

    • Basic form handling:
    import React, { useState } from 'react';
    
    const SimpleForm = () => {
      const [name, setName] = useState('');
    
      const handleSubmit = (event) => {
        event.preventDefault();
        alert(`Submitting Name: ${name}`);
      }
    
      return (
        <form onSubmit={handleSubmit}>
          <label>
            Your Name:
            <input type="text" value={name} onChange={(e) => setName(e.target.value)} />
          </label>
          <input type="submit" value
    
    
  8. Working with Forms in React

    • Basic form handling:
    import React, { useState } from "react";
    
    const SimpleForm = () => {
      const [name, setName] = useState("");
    
      const handleSubmit = event => {
        event.preventDefault();
        alert(`Submitting Name: ${name}`);
      };
    
      return (
        <form onSubmit={handleSubmit}>
          <label>
            Your Name:
            <input
              type="text"
              value={name}
              onChange={e => setName(e.target.value)}
            />
          </label>
          <input type="submit" value="Submit" />
        </form>
      );
    };
    
    export default SimpleForm;
    
  9. Routing with React Router

    • Basic routing:
    import React from "react";
    import { BrowserRouter as Router, Route, Switch } from "react-router-dom";
    import Home from "./Home";
    import About from "./About";
    
    const AppRouter = () => (
      <Router>
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/about" component={About} />
        </Switch>
      </Router>
    );
    
    export default AppRouter;
    
  10. State Management

    • Simple Redux usage (this would actually be split across multiple files in a real application):
    import { createStore } from "redux";
    import { Provider, connect } from "react-redux";
    
    // This is your reducer
    const counter = (state = 0, action) => {
      switch (action.type) {
        case "INCREMENT":
          return state + 1;
        case "DECREMENT":
          return state - 1;
        default:
          return state;
      }
    };
    
    let store = createStore(counter);
    
    const Counter = props => (
      <div>
        <p>{props.count}</p>
        <button onClick={props.increment}>+</button>
        <button onClick={props.decrement}>-</button>
      </div>
    );
    
    const mapStateToProps = state => ({
      count: state,
    });
    
    const mapDispatchToProps = dispatch => ({
      increment: () => dispatch({ type: "INCREMENT" }),
      decrement: () => dispatch({ type: "DECREMENT" }),
    });
    
    const ConnectedCounter = connect(
      mapStateToProps,
      mapDispatchToProps
    )(Counter);
    
    const App = () => (
      <Provider store={store}>
        <ConnectedCounter />
      </Provider>
    );
    
    export default App;
    
  11. Testing in React

    • Basic test with Jest and React Testing Library (this would be in a separate test file):
    import { render, fireEvent } from "@testing-library/react";
    import Counter from "./Counter";
    
    test("increments count", () => {
      const { getByText } = render(<Counter />);
      const count = getByText("0");
      const button = getByText("+");
    
      fireEvent.click(button);
    
      expect(count.textContent).toBe("1");
    });
    
  12. Deploying a React App

    • No code here, but you would explain the process of running npm run build and then deploying the built static files to a hosting service.
  13. Next Steps

    • No code here, but you could provide links to documentation or tutorials on libraries like Styled Components, Axios, Next.js, and Gatsby.js

Previous Post
How to add an estimated reading time in AstroPaper
Next Post
AstroPaper 3.0