Skip to main content

React : Building a Multi-Page React Application with .NET Web API Integration using HTTP Interceptors

 

In this blog post, we'll explore how to create a multi-page React application that communicates with a .NET Web API backend. We'll leverage HTTP interceptors in React to handle API requests and responses, allowing seamless integration between the frontend and backend. Additionally, we'll design the application to support dynamic pages, making it easy to add new features in the future.

Step 1: Set Up the .NET Web API: Begin by creating a .NET Web API project to serve as the backend for our React application. Define endpoints to handle various CRUD operations or any other functionality required by the frontend.

Step 2: Create React Application: Generate a new React application using Create React App. This will set up the basic structure and dependencies for our frontend.

npx create-react-app my-react-app
cd my-react-app
Step 3: Implement HTTP Interceptors in React: Create a custom HTTP interceptor in React to intercept API requests and responses. This allows us to add headers, handle authentication, or perform error handling globally.
// httpInterceptor.js
import axios from 'axios';

axios.interceptors.request.use(
  (config) => {
    // Add authentication token or other headers if needed
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

axios.interceptors.response.use(
  (response) => {
    // Handle successful response
    return response;
  },
  (error) => {
    // Handle error response
    return Promise.reject(error);
  }
);

export default axios;
Step 4: Create Pages and Components: Design your React application with multiple pages and reusable components. Each page should correspond to a specific feature or functionality of your application.
// HomePage.js
import React from 'react';

const HomePage = () => {
  return (
    <div>
      <h1>Welcome to My React App</h1>
      <p>This is the home page of our application.</p>
    </div>
  );
}

export default HomePage;
Step 5: Implement Routing: Set up routing in your React application using React Router. Define routes for each page and handle navigation between them.
// App.js
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import HomePage from './pages/HomePage';
// Import other pages

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={HomePage} />
        {/* Define routes for other pages */}
      </Switch>
    </Router>
  );
}

export default App;
Let's add two more pages to our React application and adjust the code snippets accordingly.
Create Additional Pages: Create two more pages in your React application to demonstrate multiple pages. For example, let's create a "AboutPage.js" and "ContactPage.js".
// AboutPage.js
import React from 'react';

const AboutPage = () => {
  return (
    <div>
      <h1>About Us</h1>
      <p>This is the About page of our application.</p>
    </div>
  );
}

export default AboutPage;
// ContactPage.js
import React from 'react';

const ContactPage = () => {
  return (
    <div>
      <h1>Contact Us</h1>
      <p>This is the Contact page of our application.</p>
    </div>
  );
}

export default ContactPage;
Update Routing: Adjust the routing in your React application to include the new pages.
// App.js
import React from 'react';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import HomePage from './pages/HomePage';
import AboutPage from './pages/AboutPage'; // New page
import ContactPage from './pages/ContactPage'; // New page

const App = () => {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={HomePage} />
        <Route exact path="/about" component={AboutPage} /> {/* New route */}
        <Route exact path="/contact" component={ContactPage} /> {/* New route */}
      </Switch>
    </Router>
  );
}

export default App;
Update Navigation: Update the navigation menu or links in your application to navigate between the pages.
// Navigation.js
import React from 'react';
import { Link } from 'react-router-dom';

const Navigation = () => {
  return (
    <nav>
      <ul>
        <li><Link to="/">Home</Link></li>
        <li><Link to="/about">About</Link></li>
        <li><Link to="/contact">Contact</Link></li>
      </ul>
    </nav>
  );
}

export default Navigation;
With these changes, your React application now includes multiple pages (Home, About, and Contact), each with its own route and corresponding component. Users can navigate between these pages using the navigation menu or links. This setup allows for a more dynamic and engaging user experience in your web application.

Step 6: Make API Calls: Integrate API calls into your React components to fetch data from the backend. Use the custom HTTP interceptor we created earlier to handle API requests.
// ExampleComponent.js
import React, { useEffect, useState } from 'react';
import httpInterceptor from '../httpInterceptor';

const ExampleComponent = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    httpInterceptor.get('/api/data')
      .then(response => {
        setData(response.data);
      })
      .catch(error => {
        console.error('Error fetching data:', error);
      });
  }, []);

  return (
    <div>
      {data ? (
        <p>Data: {data}</p>
      ) : (
        <p>Loading...</p>
      )}
    </div>
  );
}

export default ExampleComponent;
Conclusion: By following the steps outlined in this blog post, you can create a multi-page React application that communicates with a .NET Web API backend using HTTP interceptors. This setup allows for efficient API integration, dynamic page navigation, and easy addition of new features in the future. With React's component-based architecture and .NET Web API's robust backend capabilities, you can build powerful and scalable web applications.

Comments

Popular posts from this blog

Implementing and Integrating RabbitMQ in .NET Core Application: Shopping Cart and Order API

RabbitMQ is a robust message broker that enables communication between services in a decoupled, reliable manner. In this guide, we’ll implement RabbitMQ in a .NET Core application to connect two microservices: Shopping Cart API (Producer) and Order API (Consumer). 1. Prerequisites Install RabbitMQ locally or on a server. Default Management UI: http://localhost:15672 Default Credentials: guest/guest Install the RabbitMQ.Client package for .NET: dotnet add package RabbitMQ.Client 2. Architecture Overview Shopping Cart API (Producer): Sends a message when a user places an order. RabbitMQ : Acts as the broker to hold the message. Order API (Consumer): Receives the message and processes the order. 3. RabbitMQ Producer: Shopping Cart API Step 1: Install RabbitMQ.Client Ensure the RabbitMQ client library is installed: dotnet add package RabbitMQ.Client Step 2: Create the Producer Service Add a RabbitMQProducer class to send messages. RabbitMQProducer.cs : using RabbitMQ.Client; usin...

How Does My .NET Core Application Build Once and Run Everywhere?

One of the most powerful features of .NET Core is its cross-platform nature. Unlike the traditional .NET Framework, which was limited to Windows, .NET Core allows you to build your application once and run it on Windows , Linux , or macOS . This makes it an excellent choice for modern, scalable, and portable applications. In this blog, we’ll explore how .NET Core achieves this, the underlying architecture, and how you can leverage it to make your applications truly cross-platform. Key Features of .NET Core for Cross-Platform Development Platform Independence : .NET Core Runtime is available for multiple platforms (Windows, Linux, macOS). Applications can run seamlessly without platform-specific adjustments. Build Once, Run Anywhere : Compile your code once and deploy it on any OS with minimal effort. Self-Contained Deployment : .NET Core apps can include the runtime in the deployment package, making them independent of the host system's installed runtime. Standardized Libraries ...

Clean Architecture: What It Is and How It Differs from Microservices

In the tech world, buzzwords like   Clean Architecture   and   Microservices   often dominate discussions about building scalable, maintainable applications. But what exactly is Clean Architecture? How does it compare to Microservices? And most importantly, is it more efficient? Let’s break it all down, from understanding the core principles of Clean Architecture to comparing it with Microservices. By the end of this blog, you’ll know when to use each and why Clean Architecture might just be the silent hero your projects need. What is Clean Architecture? Clean Architecture  is a design paradigm introduced by Robert C. Martin (Uncle Bob) in his book  Clean Architecture: A Craftsman’s Guide to Software Structure and Design . It’s an evolution of layered architecture, focusing on organizing code in a way that makes it  flexible ,  testable , and  easy to maintain . Core Principles of Clean Architecture Dependency Inversion : High-level modules s...