React
Published in React
avatar
4 minutes read

React-router URLs dont Work When Refreshing or Writing Manually

React-router URLs dont Work When Refreshing or Writing Manually

When using React Router to handle routing in a Single Page Application (SPA), you may encounter an issue where the URLs work fine when navigating through links within the application, but they don't work as expected when refreshing the page or manually typing the URL in the address bar.

#1. Server-Side Configuration

To fix this issue, you need to configure your server to handle the routing correctly. For most SPAs, the server needs to redirect all requests to the main index.html file, where the React application is loaded.

Example with Express.js

If you are using Express.js as your server, you can use the following configuration to redirect all requests to the index.html file:

const express = require('express');
const path = require('path');

const app = express();

// Serve static files from the 'build' folder
app.use(express.static(path.join(__dirname, 'build')));

// Redirect all requests to 'index.html'
app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

const port = process.env.PORT || 5000;
app.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

In this example, we serve static files from the build folder, which contains the compiled React application. Then, we use a catch-all route (app.get('/*')) to redirect all requests to the index.html file.

#2. HashRouter as an Alternative

If you cannot configure your server to handle the routing, you can use HashRouter instead of BrowserRouter in your React application. The HashRouter uses a hash symbol (#) in the URL, which is automatically handled by browsers and does not require server-side configuration.

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

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

With HashRouter, your URLs will look like http://example.com/#/about instead of http://example.com/about.

#3. Deploying to Hosting Services

When deploying your React application to hosting services like GitHub Pages or Netlify, you may need to configure the server settings appropriately. Some hosting services have specific settings for SPAs that handle routing correctly out of the box.

Refer to the documentation of your hosting service to ensure the correct server-side configuration for your React application.

0 Comment