React Tutorial

1. Setting Up React

Create a React App (using Create React App)


npx create-react-app my-app
cd my-app
npm start

This sets up a basic React app with a development server.

2. JSX (JavaScript XML)

JSX allows you to write HTML-like syntax in JavaScript.


const element = <h1>Hello, World!</h1>

You can use JavaScript expressions inside JSX using curly braces {}


const name = "John";
const element = <h1>Hello, {name}</h1>

Attributes in JSX


const element = <img src="logo.png" alt="Logo" />

Conditionals in JSX


const isLoggedIn = true;
const greeting = isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>

3. Components

Function Components


function Welcome() {
  return <h1>Hello, World!</h1>
}

Class Components (older style)


class Welcome extends React.Component {
  render() {
    return <h1>Hello, World!</h1>
  }
}

Rendering Components


const element = <Welcome />
ReactDOM.render(element, document.getElementById('root'));

4. Props (Properties)

Props allow you to pass data into components.


function Greeting(props) {
  return <h1>Hello, {props.name}</h1>
}

const element = <Greeting name="John" />

Destructuring Props


function Greeting({ name }) {
  return <h1>Hello, {name}</h1>
}

5. State

Using `useState` Hook (Functional Components)


import React, { useState } from "react";

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

State in Class Components


class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      <div>
        <p>You clicked {this.state.count} times</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>Click me</button>
      </div>
    );
  }
}

6. Events

Handling Events in JSX


function MyButton() {
  function handleClick() {
    alert("Button clicked!");
  }

  return <button onClick={handleClick}>Click me</button>
}

Passing Arguments to Event Handlers


function MyButton() {
  function handleClick(name) {
    alert(`Hello, ${name}`);
  }

  return <button onClick={() => handleClick("John")}>Click me</button>
}

7. Conditional Rendering

Using `if` Statements


function Greeting({ isLoggedIn }) {
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>
  } else {
    return <h1>Please log in.</h1>
  }
}

Using Ternary Operator


function Greeting({ isLoggedIn }) {
  return isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>
}

8. Lists and Keys

Rendering Lists


function NumberList() {
  const numbers = [1, 2, 3, 4];
  return (
    <ul>
      {numbers.map((number) => (
        <li key={number}>{number}</li>
      ))}  
    </ul>
  );
}

Using `key`

React uses key to optimize re-rendering. Make sure to provide a unique key when rendering lists.

9. useEffect Hook

The `useEffect` hook is used to perform side effects in functional components (e.g., data fetching, subscriptions).


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

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

  useEffect(() => {
    // Component did mount equivalent
    console.log("Component mounted or count changed");

    return () => {
      // Cleanup (component will unmount)
      console.log("Cleanup");
    };
  }, [count]); // Dependency array

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

Effect without Dependencies


useEffect(() => {
  console.log("This runs after every render");
});

Effect with Empty Dependencies


useEffect(() => {
  console.log("This runs once after the initial render");
}, []);

10. Context API

Creating Context:


const MyContext = React.createContext();

function App() {
  return (
    <MyContext.Provider value="Hello, world!">
      <Child />
    </MyContext.Provider>
  );
}

function Child() {
  return <Grandchild />
}

function Grandchild() {
  const value = React.useContext(MyContext);
  return <p>{value}</p>
}

11. Forms and Controlled Components

Controlled Components: The form elements are controlled by React state.


function NameForm() {
  const [name, setName] = useState("");

  function handleChange(event) {
    setName(event.target.value);
  }

  function handleSubmit(event) {
    alert("A name was submitted: " + name);
    event.preventDefault();
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" value={name} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

12. React Router

Installing React Router:


npm install react-router-dom

Basic Usage:


import { BrowserRouter as Router, Route, Switch } from "react-router-dom";

function App() {
  return (
    <Router>
      <Switch>
        <Route path="/" exact><Home /></Route>
        <Route path="/about"><About /></Route>
      </Switch>
    </Router>
  );
}

Linking Between Pages:


import { Link } from "react-router-dom";

function Navigation() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
    </nav>
  );
}

React Quick Reference Guide

1. JSX (JavaScript XML)

JSX allows you to write HTML-like syntax within JavaScript.


const element = <h1>Hello, World!</h1>

2. Components

React components are the building blocks of a React application. They can be functional or class-based.

Functional Component


const Welcome = () => {
return <h1>Hello, React!</h1>;
};

Class Component


class Welcome extends React.Component {
render() {
  return <h1>Hello, React!</h1>;
}
}

3. Props

Props are used to pass data to components.


const Welcome = (props) => {
return <h1>Hello, {props.name}!</h1>;
};

<Welcome name="Alice" />

4. State

State is used to manage data that changes over time in a component.


const Counter = () => {
const [count, setCount] = useState(0);

return (
  <div>
    <h1>Count: {count}</h1>
    <button onClick={() => setCount(count + 1)}>Increment</button>
  </div>
);
};

5. Destructuring

Destructuring is a syntax that extracts values from arrays or objects into distinct variables.

Object Destructuring:


const person = { name: "Alice", age: 25 };
const { name, age } = person;
console.log(name, age); // Outputs: Alice 25

Array Destructuring:


const numbers = [1, 2, 3];
const [first, second] = numbers;
console.log(first, second); // Outputs: 1 2

6. Spread Operator

The spread operator (<code>...</code>) is used to copy the properties of one object or array into another.

Array Spread:


const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // Outputs: [1, 2, 3, 4, 5]

Object Spread:


const obj1 = { name: "Alice", age: 25 };
const obj2 = { ...obj1, job: "Developer" };
console.log(obj2); // Outputs: { name: 'Alice', age: 25, job: 'Developer' }

7. Event Handling

React uses a synthetic event system, which wraps native events for better cross-browser compatibility.


const ClickButton = () => {
const handleClick = () => {
  alert("Button clicked!");
};

return <button onClick={handleClick}>Click Me</button>
};

8. Conditional Rendering

You can render components conditionally using operators like if, ternary, and &&.

If Statement:


const Greeting = ({ isLoggedIn }) => {
if (isLoggedIn) {
  return <h1>Welcome, User!</h1>;
} else {
  return <h1>Please Log In</h1>;
}
};

Ternary Operator:


const Greeting = ({ isLoggedIn }) => (
isLoggedIn ? <h1>Welcome, User!</h1> : <h1>Please Log In</h1>
);

9. Lifecycle Methods (Class Components)

Lifecycle methods in class components allow you to run code at different stages of a component's life.

ComponentDidMount:


class MyComponent extends React.Component {
componentDidMount() {
  console.log("Component mounted!");
}

render() {
  return <h1>Hello, World!</h1>;
}
}

ComponentWillUnmount:


class MyComponent extends React.Component {
componentWillUnmount() {
  console.log("Component will unmount!");
}

render() {
  return <h1>Goodbye, World!</h1>;
}
}

10. useEffect Hook (Functional Components)

useEffect allows you to run side effects in functional components.


import { useEffect } from 'react';

const MyComponent = () => {
useEffect(() => {
  console.log("Component mounted!");
}, []); // Empty array means this runs only once (on mount)

return <h1>Hello, World!</h1>;
};

11. useState Hook (Functional Components)

useState is used to add state to functional components.


import { useState } from 'react';

const Counter = () => {
const [count, setCount] = useState(0);

return (
  <div>
    <h1>Count: {count}</h1>
    <button onClick={() => setCount(count + 1)}>Increment</button>
  </div>
);
};

Learn how we helped 100 top brands gain success