Home > Net >  Blank display when I use link Routes in React
Blank display when I use link Routes in React

Time:01-18

If I search "http://localhost:3000/" or "http://localhost:3000/login", my display is completely blank.

app.js

import React from 'react'
import Login from './pages/login'
import Home from './pages/home'
import Error from './pages/error'
import { Link, Router, Route, Routes } from 'react-router-dom';

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

home.js

import React from "react";

const Home = () => {
  return <h1>The Home</h1>;
};
  
export default Home;

CodePudding user response:

Refactor to look like:

import { Route, Routes, BrowserRouter } from 'react-router-dom';
// ...

function App() {
  return (
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/login" element={<Login />} />
        <Route path="*" element={<Error />} />
      </Routes>
    </BrowserRouter>
  );
};

CodePudding user response:

It looks like there may be an issue with the way you are using the component from the react-router-dom library. The component should be wrapped around a component, in order to define the client-side routing.

Try changing your app.js code to the following:

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

function App() {
  return (
    <Router>
      <Switch>
        <Route exact path="/" component={Home} />
        <Route path="/login" component={Login} />
        <Route component={Error} />
      </Switch>
    </Router>
  )
}
export default App;

This will wrap your routes inside a component, and also use the Switch component to wrap the Route, and the exact prop in the Route component for the home page to only match when the path is exactly '/'

Also, make sure to import the correct components from react-router-dom.

Also, please make sure that you have imported all the components and libraries correctly.

Let me know if this helps or if there is anything else I can assist you with.

  • Related