DEV Community

loading...

React routing in production

mackr2015 profile image mackelele ・1 min read

I am new to React and I've been developing a simple react web app. Now when I have shipped my code to the server I have issues with React Routing, in my case loading different components for different url path returns 404.

To remedy this I have adjusted the server apache conf file to redirect any ErrorDocument 404 to index.html. This is a temporary fix and I would really like to understand and solve this issue moving forward.

I tried to install node on my server (Digital Ocean droplet) but in order to do so I need more resources to allocate which I don't want to do if I don't have to.

Can somebody explain to me what can I do here to resolve the issue I am having.

This project is simple but I want to continue using React and expand to a bigger projects and web app.

Here part of the code that does Routing

import React from 'react';
import Header from './components/Header/Header';
import About from './components/Pages/About/About';
import Home from './components/Pages/Home/Home';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';

// import Bootstrap from 'react-bootstrap';
import './bootstrap.min.css';
// Default overwrite 
import './app.scss';
// Roboto Font


export default function App() {
  return (
    <>
    <Header />
      <Router>
        <Switch> 
          <Route path="/" exact component={Home}/>
          <Route path="/about" component={About}/>
          <Route path="/#contact" />
        </Switch>
      </Router>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Here my component About is returning 404.

Any help appreciated.

Discussion (1)

pic
Editor guide
Collapse
bradstondev profile image
Bradston Henry

Hi Mackelele. So I totally have run into this issue before.

So without seeing you project structure or your code, I'll try and give guidance.

The big thing to note is that using React (from my experience and research on this topic), navigation is not exactly similar to standard web routing we are probably used to.

Browser Navigation from page to page has to be initiated from within the application itself once built and hosted on a server.

This stackoverflow answer does a GREAT job of explaining what's happening and the issues with React Navigation (and solutions):

stackoverflow.com/questions/279283...

I'll share some of my code so you can kind of see how I manage navigation. Hopefully it's helpful. I manually use the command this.props.history.push() to manage navigation.

If you go to my src -> pages folder, you will see a file called "JellyBeanHome.js". In the file, there is a function called*startGame()* and that's where you'll see an instance of navigation. My App.JS file looks very similar to yours so hopefully It'll all make sense.

My React code: github.com/bradstondevcode/jelly-b...