Frequently Asked Questions

React Routing & Technical Implementation

What is routing in React and why is it important?

Routing in React refers to the process of navigating users between different pages or views within a single-page application. It is crucial because it enables seamless user experiences without full page reloads, allowing developers to build dynamic, interactive web apps. React uses libraries like React Router to handle routing efficiently. Source

How do you install React Router in a React project?

To install React Router, run npm install react-router-dom in your project directory. This adds the necessary package for handling routing in React applications. Source

How do you configure routes in React using React Router?

Routes are configured by importing Routes and Route from react-router-dom, then wrapping your route definitions inside the Routes component. Each Route specifies a path and an element to render for that path. Source

What are the key components for routing in React?

The key components are Routes (which wraps all route definitions) and Route (which defines individual paths and components). Source

How do you create a navigation bar for routing in React?

You can create a navigation bar using the NavLink component from react-router-dom. NavLink allows navigation between routes and provides an active class for styling the currently active route. Source

How do you handle 'No Routes Found' errors in React Router?

To handle unmatched routes, create a route with path * and render a custom component (e.g., NoMatch) to display a 404 or 'Page Not Found' message. Source

How do you navigate programmatically in React?

Use the useNavigate hook from react-router-dom to redirect users based on actions, such as button clicks or form submissions. Source

What is dynamic routing in React and how is it implemented?

Dynamic routing allows you to create routes that accept parameters, such as /products/:slug. Use the useParams hook to access these parameters and fetch data accordingly. Source

How do you use URL parameters for dynamic routing in React?

Import the useParams hook from react-router-dom in your component to access URL parameters (e.g., slug) and use them to fetch specific data from your backend or CMS. Source

How do you implement lazy loading with React Router?

Use the lazy and Suspense components from React to load routes only when needed. Wrap your routes in Suspense and provide a fallback UI while components are loading. Source

What are the prerequisites for following the React routing guide?

You should have a basic understanding of HTML, CSS, JavaScript, some experience with React, and Node.js with npm or yarn installed. Setting up a React app using Create React App is also recommended. Source

How does Hygraph integrate with React for dynamic content?

Hygraph provides a GraphQL-native API that allows React applications to fetch and display dynamic content, such as product details, using queries based on URL parameters like slug. Source

Where can I find the source code for the cocktails app example?

The source code for the cocktails app used in the React routing guide is available on GitHub: cocktails-graphcms-react. Source

How do you style active navigation links in React Router?

Use the active class provided by NavLink or assign custom classes using the isActive property for conditional styling in your CSS. Source

How does lazy loading improve performance in React apps?

Lazy loading ensures that components not needed on the initial page are loaded only when required, reducing initial load times and improving user experience. Source

How do you fetch data from Hygraph using GraphQL in React?

Use GraphQL queries to fetch data from Hygraph based on parameters like slug. Integrate these queries in your React components to display dynamic content. Source

What is the role of the Suspense component in React routing?

The Suspense component allows you to display a fallback UI while lazy-loaded components are being fetched, improving perceived performance and user experience. Source

How can I try Hygraph for free?

You can sign up for a free developer account and start building with Hygraph's GraphQL-native API-first approach at app.hygraph.com. Source

Where can I learn more about integrating React with Hygraph?

Visit Hygraph's React CMS page for guides and resources on integrating React with Hygraph. Source

What is the benefit of using GraphQL with React and Hygraph?

GraphQL enables efficient data fetching, allowing React apps to request only the data they need from Hygraph, resulting in faster performance and reduced bandwidth usage. Source

Features & Capabilities

What features does Hygraph offer for content management?

Hygraph provides a GraphQL-native Headless CMS with features like Smart Edge Cache for fast content delivery, content federation, custom roles, rich text formatting, project backups, and extensive integration capabilities. Source

Does Hygraph support high-performance endpoints?

Yes, Hygraph has made significant improvements to its high-performance endpoints, ensuring reliability and speed for content delivery. Source

What is Smart Edge Cache in Hygraph?

Smart Edge Cache is a feature that enhances performance and accelerates content delivery, making Hygraph ideal for businesses with high traffic and global audiences. Source

How does Hygraph measure and optimize GraphQL API performance?

Hygraph measures the performance of its GraphQL API and provides practical advice for developers to optimize API usage, ensuring best possible performance for applications. Source

What security and compliance certifications does Hygraph have?

Hygraph is SOC 2 Type 2 compliant (since August 3rd, 2022), ISO 27001 certified, and GDPR compliant, ensuring robust security and data protection. Source

What security features are available in Hygraph?

Hygraph offers granular permissions, SSO integrations, audit logs, encryption at rest and in transit, regular backups, and enterprise-grade compliance features. Source

How does Hygraph support enterprise-grade compliance?

Hygraph meets enterprise requirements with dedicated hosting, custom SLAs, security certifications, and supports compliance with regulations like GDPR and CCPA. Source

What is Hygraph's process for reporting security issues?

Hygraph provides a transparent process for reporting security issues and offers a public security and compliance report for certified infrastructure. Security Report

Use Cases & Benefits

Who is the target audience for Hygraph?

Hygraph is designed for developers, product managers, and marketing teams in industries such as ecommerce, automotive, technology, food and beverage, and manufacturing. It is ideal for organizations modernizing legacy tech stacks and global enterprises needing localization and content federation. Source

What problems does Hygraph solve for businesses?

Hygraph addresses operational inefficiencies, financial challenges, and technical issues such as developer dependency, legacy tech stack modernization, content consistency, high operational costs, slow speed-to-market, integration difficulties, and performance bottlenecks. Source

How does Hygraph differentiate itself from other CMS platforms?

Hygraph stands out as the first GraphQL-native Headless CMS, offering content federation, user-friendly tools, enterprise-grade security, and advanced integration capabilities, making it highly flexible and scalable compared to competitors. Source

What customer success stories demonstrate Hygraph's impact?

Komax achieved 3X faster time-to-market, Autoweb saw a 20% increase in website monetization, Samsung improved customer engagement by 15%, and Stobag increased online revenue share from 15% to 70% after adopting Hygraph. Customer Stories

How easy is it to implement Hygraph and get started?

Implementation time varies by project. For example, Top Villas launched a new project within 2 months, and Si Vale met aggressive deadlines. Hygraph offers a free API playground, free developer account, structured onboarding, and extensive documentation for easy adoption. Documentation

What feedback have customers given about Hygraph's ease of use?

Customers praise Hygraph's intuitive UI, accessibility for non-technical users, and custom app integration. Hygraph was recognized for 'Best Usability' in Summer 2023. Source

What KPIs and metrics are associated with Hygraph's solutions?

Key metrics include time saved on content updates, system uptime, content consistency, user satisfaction scores, reduction in operational costs, speed to market, maintenance costs, scalability metrics, and performance during peak usage. CMS KPIs

What is the primary purpose of Hygraph?

Hygraph empowers businesses to build, manage, and deliver exceptional digital experiences at scale, eliminating traditional CMS pain points and providing flexibility, scalability, and efficiency for modern workflows. Source

How does Hygraph contribute to its company's vision and mission?

Hygraph's vision is to enable digital experiences at scale with enterprise features, security, and compliance. Its mission is rooted in trust, collaboration, customer focus, and continuous learning, achieved through its GraphQL-native architecture, content federation, and enterprise-grade features. Source

How does Hygraph handle value objections from prospects?

Hygraph addresses value objections by understanding customer needs, highlighting unique features, demonstrating ROI through reduced costs and accelerated speed to market, and sharing success stories like Samsung's improved engagement. Samsung Case Study

What elements are included in a blog page model in Hygraph?

A Hygraph blog page model includes slug, category, tag, title, description, authors, publishing date, cover image, content, and SEO metadata. Source

Where can I read the latest posts from the Hygraph blog?

You can read the latest posts on the Hygraph blog feed. Source

What types of articles are available on the Hygraph blog?

The Hygraph blog features articles on content strategy, headless CMS, frontend technologies, developer tutorials, announcements, and financial considerations for content platforms. Source

Where can I find a simple blog project using Hygraph?

A simple blog project using Hygraph is available at Hygraph Gatsby Blog Starter. Source

What is the significance of the Hygraph FM blog post?

The Hygraph FM blog post guides on adding pagination to Hygraph FM, enhancing user experience and SEO. Source

Introducing Click to Edit

A complete guide to routing in React

Learn how to perform routing in React using React router, as well as the various aspects of routing and how React router handles them.
Aagam Vadecha

Last updated by Aagam 

Jul 19, 2024

Originally written by Joel

A complete guide to routing in React

React is an open-source frontend JavaScript framework that allows developers to create websites and user interfaces using UI components and single-page applications. Routing is one of the most important features we always want to implement when developing these applications.

Routing redirects users to different pages based on their actions or requests. In React routing, you'll use an external library called React router, which can be challenging to configure if you need help understanding how it works.

In this article, we will show you how to perform routing in React using a React router. Learn the various routing aspects and how React router handles them, such as dynamic routing, programmatic navigation, no-matching routes, etc.

#Getting started

To fully comprehend and follow this guide, we would create an application that properly illustrates all aspects of navigation with appropriate use cases. We would create/use a cocktails app that retrieves data from Hygraph via GraphQL. This application, which can be accessed via this live link, uses all aspects of routing covered in this guide.

The Hygraph schema for a 'Cocktail' content model, showing the 'slug' field used for dynamic routing in React

Editor's Note

Note: This guide only covers routing; however, the aspect of creating a schema on Hygraph and how we consumed the data will not be covered; notwithstanding, here is a link to the source code, and I have also included a picture of what the schema looks like in this article.

Prerequisite

You should have the following to follow along with this guide and code:

  • A fundamental understanding of HTML, CSS, and JavaScript
  • Some experience or knowledge of React
  • Node and npm or yarn installed on your machine
  • Set up a React Application using Create React App

#Adding React router to our app

How to install React router

As previously stated, React makes use of an external library to handle routing; however, before we can implement routing with that library, we must first install it in our project, which is accomplished by running the following command in your terminal (within your project directory):

npm install react-router-dom

After successfully installing the package, we can set up and configure the React router for our project.

The Product Launch That Redefines Headless CMS

See how Hygraph uses AI to drive content speed and precision.

How to setup React router

To configure React router, navigate to the index.js file, which is the root file, and import BrowserRouter from the react-router-dom package that we installed, wrapping it around our App component as follows:

// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import App from './App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</React.StrictMode>
);

#How to configure routes in React

We have now successfully installed and imported React router into our project; the next step is to use React router to implement routing. The first step is configuring all of our routes (all the pages/components we want to navigate).

We would first create those components, in our case, three pages: the Home page, the About Page, and the Products Page. This GitHub repository contains the content for these pages. Once those pages are properly configured, we can now set up and configure our routes in the App.js file, which serves as the foundation for our React application:

// App.js
import { Routes, Route } from 'react-router-dom';
import Home from './Pages/Home';
import About from './Pages/About';
import Products from './Pages/Products';
const App = () => {
return (
<>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/products" element={<Products />} />
<Route path="/about" element={<About />} />
</Routes>
</>
);
};
export default App;

We can see in the above code that we imported Routes and Route components from react-router-dom and then used them to declare the routes we want. All Routes are wrapped in the Routes tag, and these Routes have two major properties:

  • path: As the name implies, this identifies the path we want users to take to reach the set component. When we set the path to /about, for example, when the user adds /about to the URL link, it navigates to that page.

  • element: This contains the component that we want the set path to load. This is simple to understand, but remember to import any components we are using here, or else an error will occur.

Editor's Note

We created a folder (Pages) to keep all page components separate from actual components.

When we go to our browser and try to navigate via the URL, it will load whatever content we have on such pages.

Adding a navigation bar

Let us now create a standard Navigation bar component that can be used to navigate inside our application.

First, create the Navbar component.

// component/NavBar.js
import { NavLink } from "react-router-dom";
const NavBar = () => {
return (
<nav>
<ul>
<li>
<NavLink to="/">Home</NavLink>
</li>
<li>
<NavLink to="/about">About</NavLink>
</li>
<li>
<NavLink to="/products">Products</NavLink>
</li>
</ul>
</nav>
);
};
export default NavBar;

The NavLink component from react-router-dom is a special component that helps you navigate different routes using the to prop. The NavLink component also knows whether the route is currently "active" and adds a default active class to the link. We can use this class in our CSS to define some styling for active links, as shown below:

// index.css
ul li a {
color: #000;
}
ul li a:hover {
color: #00a8ff;
}
ul li a.active {
color: #00a8ff;
}

Also, we can assign our custom classes instead of using the default active class. The NavLink component gives us access to properties like isActive, which can be used like this.

...
<li>
<NavLink
to="/"
className={({ isActive }) => {
return isActive ? "active-link" : "";
}}
>
Home
</NavLink>
</li>
...

Finally, let us use the Navbar component inside our App.

// App.js
import NavBar from "./Components/Navbar";
import { Routes, Route } from "react-router-dom";
const App = () => {
return (
<>
<NavBar />
<Routes>
...
</Routes>
</>
);
};
export default App;

How to fix No Routes Found Error

When routing, a situation may cause a user to access an unconfigured route or a route that does not exist; when this occurs, React does not display anything on the screen except a warning with the message "No routes matched location."

This can be fixed by configuring a new route to return a specific component when a user navigates to an unconfigured route as follows:

// App.js
import { Routes, Route } from 'react-router-dom';
import NoMatch from './Components/NoMatch';
const App = () => {
return (
<>
<Routes>
// ...
<Route path="*" element={<NoMatch />} />
</Routes>
</>
);
};
export default App;

In the preceding code, we created a route with the path * to get all non-configured paths and assign them to the attached component.

Editor's Note

We created a component called NoMatch.js, but you can name yours whatever you want to display 404, page not found, on the screen, so users know they are on the wrong page. We can also add a button that takes the user to another page or back, which leads us to programmatic navigation.

#How to navigate programmatically in React

Programmatic navigation is the process of navigating/redirecting a user as a result of an action on a route, such as a login or a signup action, order success, or when he clicks on a back button.

Let's first look at how we can redirect to a page when an action occurs, such as when a button is clicked. We accomplish this by adding an onClick event, but first, we must create the route in our App.js file. After that, we can import the useNavigate hook from the react-router-dom and use it to navigate programmatically as follows:

// Products.js
import { useNavigate } from 'react-router-dom';
const Products = () => {
const navigate = useNavigate();
return (
<div className="container">
<div className="title">
<h1>Order Product CockTails</h1>
</div>
<button className="btn" onClick={() => navigate('order-summary')}>
Place Order
</button>
</div>
);
};
export default Products;

Editor's Note

We already created a route with the path order-summary, so when this button is clicked, the user is automatically navigated to the orderSummary component attached to this route.
<button className="btn" onClick={() => navigate(-1)}>
Go Back
</button>

Ensure you already have the hook imported and instantiated as we did earlier else this won’t work.

#How to implement dynamic routing with React router

We created three files in our pages folder earlier to implement routing, one of which was the products component, which we will populate with Hygraph content. We created a schema in Hygraph to receive cocktail details, and this is how it looks:

your content model in hygraph

We then filled it in with cocktail specifics. We will now use GraphQL to retrieve these data so that we can consume them in our React project. This is how the products page appears:

// Products.js
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { getAllCocktails } from "../api";
import ProductCard from "../Components/ProductCard";
const Products = () => {
const [products, setProducts] = useState([]);
const navigate = useNavigate();
useEffect(() => {
const fetchProducts = async () => {
const { cocktails } = await getAllCocktails();
setProducts(cocktails);
};
fetchProducts();
}, []);
return (
<div className="container">
<button className="btn" onClick={() => navigate(-1)}>
Go Back
</button>
<div className="title">
<h1>CockTails</h1>
</div>
<div className="cocktails-container">
{products.map((product) => (
<ProductCard product={product} />
))}
</div>
</div>
);
};
export default Products;
// components/ProductCard.js
import { Link } from "react-router-dom";
const ProductCard = ({ product }) => {
if (!product) {
return null;
}
return (
<div key={product.id} className="cocktail-card">
<img src={product.image.url} alt="" className="cocktail-img" />
<div className="cocktail-info">
<div className="content-text">
<h2 className="cocktail-name">{product.name}</h2>
<span className="info">{product.info}</span>
</div>
<Link to={`/products/${product.slug}`}>
<div className="btn">View Details</div>
</Link>
</div>
</div>
);
};
export default ProductCard;

Editor's Note

You can learn more about React and Hygraph here.

We fetched our content from Hygraph in the preceding code; if you already created your own schema, you can simply change the Endpoint URL and possibly the schema name if you gave it a different name.

Editor's Note

We added a button on each cocktail card so that a user can click it to view more details about each cocktail, but this would be done dynamically because we can create different components for each cocktail, which would be stressful if we had more than 5 different cocktails. Dynamic routing comes into play here.

We added a Link and used string interpolation to dynamically attach the slug of each product to the path, so we can get the slug and use it to get the data to show.

Let us now put dynamic routing into action.

The first step would be to create the component that we want to render dynamically, and for that we would create a ProductDetials.js file where we would dynamically fetch details of each product based on the slug passed through the URL, but for now we can just place dummy data into the component like this:

// ProductDetails.js
const ProductDetails = () => {
return (
<div className="container">
<h1>Products Details Page</h1>
</div>
);
};
export default ProductDetails;

We can now proceed to create a route to handle dynamic routing in our App.js file this way:

// App.js
import { Routes, Route } from 'react-router-dom';
// ...
import ProductDetails from './Pages/ProductDetails';
const App = () => {
return (
<>
<Routes>
// ...
<Route path="/products/:slug" element={<ProductDetails />} />
</Routes>
</>
);
};
export default App;

Editor's Note

We used slug, which can be anything, but this route will match any value and display the component as long as the pattern is the same, for example, http://localhost:3000/products/cocktail will show the ProductDetails component.

So far, we've dealt with the first part of dynamic routing. We must now obtain the parameter passed through the URL in order to dynamically query the data for the specific cocktail. This will be accomplished through the use of urlParams.

How to use URL params to handle dynamic routing

We will import the useParams hook into the ProductDetails component so that we can use it to get the URL parameter and then use that parameter to query our data from Hygraph via GraphQL.

// ProductDetails.js
import { useState, useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { getProductBySlug } from "../api";
const ProductDetails = () => {
const [product, setProduct] = useState([]);
const navigate = useNavigate();
// Fetch slug from route parameters
const { slug } = useParams();
useEffect(() => {
const fetchProduct = async () => {
const { cocktail } = await getProductBySlug(slug);
setProduct(cocktail);
};
fetchProduct();
}, [slug]);
return (
<div className="container">
// ...Product Details template
</div>
);
};
export default ProductDetails;

At this point, we have successfully been able to get the URL param passed, let’s now make use of this slug to fetch data from Hygraph using GraphQL:

At this point, we have successfully implemented dynamic routing.

#How to implement lazy loading with React router

We've already seen how to create routes and implement routing with React router; now let's look at how to lazy load routes with React router.

Lazy loading is a technique in which components that are not required on the home page are not loaded until a user navigates to that page, allowing our application to load faster than having to wait for the entire app to load at once. This contributes to improved performance, which leads to a positive user experience.

To implement lazy loading, simply go to App.js and wrap our routes with the Suspense component, along with a fallback props that are rendered on the screen until the component loads:

// App.js
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
import NavBar from './Components/NavBar';
const Home = lazy(() => import('./Pages/Home'));
const About = lazy(() => import('./Pages/About'));
const Products = lazy(() => import('./Pages/Products'));
const ProductDetails = lazy(() => import('./Pages/ProductDetails'));
const NoMatch = lazy(() => import('./Components/NoMatch'));
const App = () => {
return (
<>
<NavBar />
<Suspense fallback={<div className="container">Loading...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:slug" element={<ProductDetails />} />
<Route path="*" element={<NoMatch />} />
</Routes>
</Suspense>
</>
);
};
export default App;

Editor's Note

We wrapped the routes with the Suspense component, and it’s important for you to know that the fallback props can hold a component.

#Conclusion

We learned about routing and how to implement it in our React application in this guide. It is critical to understand that the React router is what allows us to perform single-page routing without reloading the application.

Try Hygraph for free

Build limitless solutions rapidly with our GraphQL-native API-first approach

Blog Authors

Share with others

Sign up for our newsletter!

Be the first to know about releases and industry news and insights.