简体   繁体   中英

Why is BrowserRouter and Route from 'react-router-dom' not working properly?

These are the contents of the project directory named my-app .

node_modules
package-lock.json
package.json
public
└── index.html
src
├── App.js
├── index.js
└── pages
    └── Home.js

public/index.html

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <!-- all the components are displayed in this #root element -->
    <div id="root"></div>
  </body>
</html>

src/App.js

import {BrowserRouter, Route, Link, Switch} from 'react-router-dom';
import ReactDOM from 'react-dom';
import Home from './pages/Home';

function App() {
        return <>
                <BrowserRouter>
                        <Route exact path="/" component={Home}></Route>
                </BrowserRouter>
        </>;
}
export default App;

src/index.js

import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(
    <App />,
    document.getElementById("root")
);

src/pages/Home.js

function Home() {
        return <h1>Homepage</h1>
}
export default Home;

When I run npm start in the my-app directory, the project compiles with the following message:

Compiled successfully!

You can now view my-app in the browser.

  Local:            http://localhost:3000
  On Your Network:  http://<network_ip>:3000

Note that the development build is not optimized.
To create a production build, use npm run build.

asset static/js/bundle.js 1.49 MiB [emitted] (name: main) 1 related asset
asset index.html 334 bytes [emitted]
asset asset-manifest.json 190 bytes [emitted]
cached modules 1.39 MiB (javascript) 28.1 KiB (runtime) [cached] 109 modules
webpack 5.66.0 compiled successfully in 1509 ms

When I open http://localhost:3000 on a web browser though, I get a blank page, which means that no JSX / HTML is rendered into the #root div at public/index.html . This only happens when I introduce the lines with BrowserRouter and Router tags. Is someone else able to reproduce this error? I can't figure out what's wrong with this!

Edit: Here are the versions of node, npx and npm that I'm using.

:~$ node -v
v16.13.2
:~$ npm -v
8.1.2
:~$ npx -v
8.1.2

Since react-router-dom v6, some props changed for components that it exposes such as Route , and Switch is replaced by Routes :

Here is your code modified to match with new changes:

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />}></Route>
      </Routes>
    </BrowserRouter>
  );
}
export default App;

Also, no need for <> (aka React.Fragment since BrowserRouter is the only item present in jsx.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM