I wrote a small piece of code to understand react router, I have set up routes /
, /aboutme
and /contact
. The problem is only the /
route works, The other routes won't render. There is no error in the console either and the /
route works at localhost:8080/#!/
or localhost:8080/#!
not at localhost:8080
as I thought it would. I am using webpack 4 to bundle files. Is there something wrong with my config file that's causing this issue?
I tried accessing routes at
http://localhost:8080/#!/aboutme
http://localhost:8080/#!/contact
only the root component is rendered in both the cases
http://localhost:8080/aboutme
throws cannot get/url
http://localhost:8080/contact
throws cannot get/url
I don't understand what I am doing wrong please take look.
import React from "react"; import ReactDOM from "react-dom"; import { BrowserRouter as Router } from 'react-router-dom' import Route from 'react-router-dom/Route' const root= (props) => { return ( <p>hello</p> ) } const about= (props) => { return ( <p>About me -_-</p> ) } const contact= (props) => { return ( <p>contact info</p> ) } const App = () => { return ( <Router> <div> <Route path="/" exact component={root} /> <Route path="/aboutme" exact component={about} /> <Route path="/contact" exact component={contact} /> </div> </Router> ) } ReactDOM.render(<App />, document.getElementById("index"));
my webpack config
const HtmlWebPackPlugin = require("html-webpack-plugin"); const path = require('path'); const htmlPlugin = new HtmlWebPackPlugin({ template: "./src/index.html", filename: "./index.html" }); module.exports = { output: { path: path.resolve(__dirname, 'dist'), filename: 'index_bundle.js', }, module: { rules: [ { test: /\\.js$/, exclude: /node_modules/, use: { loader: "babel-loader" } }, { test: /\\.css$/, exclude: /node_modules/, use: ['style-loader', 'css-loader'] } ] }, plugins: [htmlPlugin] };
Use <Switch />
Component to render only one component for one route and pass exact prop to Route, it will only render if the full path is matched.
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Switch } from "react-router-dom";
import Route from "react-router-dom/Route";
const root = props => {
return <p>hello</p>;
};
const about = props => {
return <p>About me -_-</p>;
};
const contact = props => {
return <p>contact info</p>;
};
const pageNotFound = props => {
return <p>page not found.</p>;
};
const App = () => {
return (
<Router>
<Switch>
<Route path="/" exact component={root} exact />
<Route path="/aboutme" exact component={about} exact />
<Route path="/contact" exact component={contact} exact />
<Route component={pageNotFound} />
</Switch>
</Router>
);
};
ReactDOM.render(<App />, document.getElementById("index"));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.