Contents

Implementing Features in a React Application

Once your components are created and styled, the next steps involve adding routing and navigation, implementing CRUD (Create, Read, Update, Delete) operations, and integrating with external APIs to make your application dynamic and interactive.

Adding Routing and Navigation

Routing allows you to navigate between different views or pages in your application without reloading the entire page. React Router is the most popular library for handling routing in React.

Step 1: Set Up React Router

If you haven’t installed React Router yet, you can do so with:

				
					npm install react-router-dom


				
			

Step 2: Define Routes in Your Application

You need to wrap your application with BrowserRouter and define routes using the Route component.

Example:

				
					// App.js
import React from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import Home from './components/Home';
import TaskList from './components/TaskList';
import TaskDetail from './components/TaskDetail';
import NotFound from './components/NotFound';
import Header from './components/Header';

function App() {
  return (
    <Router>
      <div>
        <Header />
        <Switch>
          <Route path="/" exact component={Home} />
          <Route path="/tasks" exact component={TaskList} />
          <Route path="/tasks/:id" component={TaskDetail} />
          <Route component={NotFound} />
        </Switch>
      </div>
    </Router>
  );
}

export default App;


				
			

Step 3: Create Navigation Links

Use the Link or NavLink components from react-router-dom to create navigation links between different routes.

Example:

				
					// Header.js
import React from 'react';
import { NavLink } from 'react-router-dom';

function Header() {
  return (
    <nav>
      <ul>
        <li>
          <NavLink exact to="/" activeClassName="active">
            Home
          </NavLink>
        </li>
        <li>
          <NavLink to="/tasks" activeClassName="active">
            Tasks
          </NavLink>
        </li>
      </ul>
    </nav>
  );
}

export default Header;


				
			

Implementing CRUD Operations

CRUD operations are essential for managing data within your application. These operations correspond to creating, reading, updating, and deleting data.

Step 1: Set Up the State and Actions

You need state management (using useState, Redux, etc.) to manage the data that will be created, read, updated, or deleted.

Example Using useState:

				
					// TaskList.js
import React, { useState } from 'react';
import TaskItem from './TaskItem';

function TaskList() {
  const [tasks, setTasks] = useState([
    { id: 1, title: 'Task 1', completed: false },
    { id: 2, title: 'Task 2', completed: false },
  ]);

  const addTask = (title) => {
    const newTask = {
      id: tasks.length + 1,
      title,
      completed: false,
    };
    setTasks([...tasks, newTask]);
  };

  const updateTask = (id, updatedTitle) => {
    setTasks(
      tasks.map((task) =>
        task.id === id ? { ...task, title: updatedTitle } : task
      )
    );
  };

  const deleteTask = (id) => {
    setTasks(tasks.filter((task) => task.id !== id));
  };

  return (
    <div>
      <h2>Task List</h2>
      <ul>
        {tasks.map((task) => (
          <TaskItem
            key={task.id}
            task={task}
            onUpdate={updateTask}
            onDelete={deleteTask}
          />
        ))}
      </ul>
      <button onClick={() => addTask('New Task')}>Add Task</button>
    </div>
  );
}

export default TaskList;


				
			

Step 2: Create TaskItem Component to Handle Individual Tasks

Example:

				
					// TaskItem.js
import React from 'react';

function TaskItem({ task, onUpdate, onDelete }) {
  const handleUpdate = () => {
    const updatedTitle = prompt('Update task title:', task.title);
    if (updatedTitle) {
      onUpdate(task.id, updatedTitle);
    }
  };

  return (
    <li>
      <span>{task.title}</span>
      <button onClick={handleUpdate}>Update</button>
      <button onClick={() => onDelete(task.id)}>Delete</button>
    </li>
  );
}

export default TaskItem;


				
			

Integrating with External APIs

Integrating with external APIs allows you to fetch, post, update, or delete data from a server or a third-party service.

Step 1: Choose an API

Identify the API you need to integrate with. For example, you might use the JSONPlaceholder API for testing or a custom backend API for your application.

Step 2: Fetch Data from an API

Use the useEffect hook and fetch (or axios) to fetch data from an API when the component mounts.

Example:

				
					// TaskList.js
import React, { useState, useEffect } from 'react';

function TaskList() {
  const [tasks, setTasks] = useState([]);

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos')
      .then((response) => response.json())
      .then((data) => setTasks(data.slice(0, 10)));
  }, []);

  return (
    <div>
      <h2>Task List</h2>
      <ul>
        {tasks.map((task) => (
          <li key={task.id}>{task.title}</li>
        ))}
      </ul>
    </div>
  );
}

export default TaskList;


				
			

Step 3: Post Data to an API

You can post new data to the API when a user adds a new task.

Example:

				
					const addTask = (title) => {
  const newTask = {
    title,
    completed: false,
  };

  fetch('https://jsonplaceholder.typicode.com/todos', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(newTask),
  })
    .then((response) => response.json())
    .then((data) => {
      setTasks([...tasks, data]);
    });
};


				
			

Step 4: Update and Delete Data

Similar to fetching and posting data, you can update and delete data by sending PUT or DELETE requests to the API.

Example of Deleting a Task:

				
					const deleteTask = (id) => {
  fetch(`https://jsonplaceholder.typicode.com/todos/${id}`, {
    method: 'DELETE',
  }).then(() => {
    setTasks(tasks.filter((task) => task.id !== id));
  });
};


				
			

Conclusion

Implementing features like routing and navigation, CRUD operations, and integrating with external APIs are essential steps in building a fully functional React application. Routing allows for a seamless user experience, CRUD operations manage your application’s data, and API integration connects your app with external services. Mastering these techniques will enable you to build more dynamic, interactive, and powerful React applications.