Reputation: 3290
I am new to ReactJS and facing an issue with Routing. This is my App.js file where I have defined my React Router.
import React from "react";
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Home from "./Home";
import About from "./About";
import Feedback from "./Feedback"
import Chunking from "./Chunking"
export default class App extends React.Component {
render() {
return(
<Router>
<div>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<div class="navbar-nav">
<Link class="nav-item nav-link" to="/">Home <span class="sr-only">(current)</span></Link>
<Link class="nav-item nav-link" to="/about">About</Link>
<Link class="nav-item nav-link" to="/feedback">Feedback</Link>
<Link class="nav-item nav-link" to="/chunking">Chunking</Link>
</div>
</div>
</nav>
<hr class="my-4" />
<div id="mainContentContainer">
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/feedback" component={Feedback} />
<Route path="/chunking" component={Chunking} />
</div>
</div>
</Router>
);
}
}
When I start the server and render the page in browser the page loads perfectly.
Even the Links in the Navbar is working perfectly. The appropriate component gets rendered on clicking the Links in the Navbar.
The issue is, I am not able to render the page when I am trying to load the page with the full path name. Like:-
http://localhost:8080/about
http://localhost:8080/feedback
The page gets rendered only for the url http://localhost:8080/
From the Home Page I am able to navigate to all the other pages, but when I am typing the url http://localhost:8080/about in my browser and pressing enter I am getting an error like this -
The About component class looks like this -
import React from "react";
export default class About extends React.Component {
render() {
return (
<div>
<h2>About Page</h2>
</div>
);
}
}
How can I get other urls to work in my application when requested directly?
Upvotes: 2
Views: 2598
Reputation: 1760
This could be something of serve configuration as @user3526468 says. Try to modify this inside your webpack.config.js
> devServer
:
devServer = {
host: 'localhost',
port: 8080,
contentBase: PATH.join(__dirname, '/src'), // This is were I store content of my project. Ir your case, could be different
hot: true,
inline: true,
historyApiFallback: true // THIS LINE WILL SOLVE YOUR PROBLEM
};
I hope it solves your problem. Regards.
Upvotes: 2
Reputation: 354
When you type localhost:8080/about
, the browser makes a request to your server, and apparently your server does not know it has to load your react code on other routes besides /
. Make sure you configure your server correctly (for example to render the same react code independent of the route), and then react router will be able to handle your routes.
Upvotes: 0