React

React is a popular JavaScript library for building user interfaces. It follows a component-based architecture, allowing developers to create reusable UI components that efficiently update and render when the underlying data changes. React utilizes a virtual DOM (Document Object Model) for efficient rendering, resulting in fast and responsive user interfaces. It provides a declarative syntax, enabling developers to describe the desired UI state, and React takes care of updating the actual UI. With its emphasis on reusability, performance, and community support, React has become a go-to choice for building interactive and scalable web applications.

Module 1: Introduction to React

Introduction to React

React is a JavaScript library for building user interfaces. It is maintained by Facebook and a community of individual developers and companies.

import React from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.getElementById('root')
);

Components and Props

Components let you split the UI into independent, reusable pieces. Props allow you to pass data from parent to child components.

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

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

State and Lifecycle

State allows React components to change their output over time in response to user actions, network responses, and anything else.

class Clock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {date: new Date()};
  }

  render() {
    return (
      <div>
        <h1>Hello, world!</h1>
        <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
      </div>
    );
  }
}

Module 2: Advanced React

Handling Events

Handling events with React elements is very similar to handling events on DOM elements. There are some syntactic differences.

class Toggle extends React.Component {
  constructor(props) {
    super(props);
    this.state = {isToggleOn: true};

    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    this.setState(state => ({
      isToggleOn: !state.isToggleOn
    }));
  }

  render() {
    return (
      <button onClick={this.handleClick}>
        {this.state.isToggleOn ? 'ON' : 'OFF'}
      </button>
    );
  }
}

Context

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

const ThemeContext = React.createContext('light');

class App extends React.Component {
  render() {
    return (
      <ThemeContext.Provider value="dark">
        <ThemedButton />
      </ThemeContext.Provider>
    );
  }
}

function ThemedButton(props) {
  return (
    <ThemeContext.Consumer>
      {theme => <Button {...props} theme={theme} />}
    </ThemeContext.Consumer>
  );
}

Hooks

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

import React, { useState } from 'react';

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

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

Module 3: React Routing and State Management

React Router

React Router is a standard library for routing in React. It enables the navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.

import { BrowserRouter as Router, Route, Link } from 'react-router-dom';

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li><Link to='/'>Home</Link></li>
            <li><Link to='/about'>About</Link></li>
          </ul>
        </nav>
        <Route path='/' exact component={Home} />
        <Route path='/about' component={About} />
      </div>
    </Router>
  );
}

State Management with Redux

Redux is a predictable state container for JavaScript apps. It helps you write applications that behave consistently, run in different environments (client, server, and native), and are easy to test.

import { createStore } from 'redux';

function counter(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;
    case 'DECREMENT':
      return state - 1;
    default:
      return state;
  }
}

let store = createStore(counter);

store.subscribe(() => console.log(store.getState()));

store.dispatch({ type: 'INCREMENT' });

Module 4: React and RESTful APIs

Fetching Data

One common task in developing apps is connecting to a RESTful API to fetch or send data. In React, this can be handled in various ways, but the simplest and most commonly used method is using the Fetch API or the Axios library.

fetch('https://api.mydomain.com')
.then(response => response.json())
.then(data => console.log(data));

Using Data

Once data has been fetched, it can be stored in the component's state and used in the render function to display dynamic content.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { data: [] };
  }

  componentDidMount() {
    fetch('https://api.mydomain.com')
    .then(response => response.json())
    .then(data => this.setState({ data }));
  }

  render() {
    return (
      <div>{this.state.data.map(item => <div key={item.id}>{item.name}</div>)}</div>
    );
  }
}

Module 5: Testing and Deploying React Applications

Unit Testing with Jest and React Testing Library

Jest is a popular testing framework that works well with React and React Testing Library is a simple and complete set of React DOM testing utilities that encourage good testing practices. Together, they provide a powerful toolset for testing React components.

import { render, fireEvent } from '@testing-library/react';
import Button from './Button';

test('check button click event', () => {
  const handleClick = jest.fn();
  const { getByText } = render(<Button onClick={handleClick}>Click Me</Button>);
  fireEvent.click(getByText(/Click Me/i));
  expect(handleClick).toHaveBeenCalledTimes(1);
});

Deployment

Deploying a React app is the process of putting a React app into production. Common platforms for deploying React apps include AWS, Heroku, and Netlify.

// Build your application for production
npm run build

// Your application is ready to be deployed.