Home > Mobile >  My page goes blank when I call Router from "react-router-dom". What did I do wrong?
My page goes blank when I call Router from "react-router-dom". What did I do wrong?

Time:03-10

This is the App.js file I run

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Route,
} from 'react-router-dom';
import HomePage from './pages/HomePage';
import './App.css';


class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          <Route path="/" component={HomePage} exact />
        </div>
      </Router>
    );
  }
}
  


export default App;

I keep getting a blank file, but It displays if I comment out the Router

CodePudding user response:

In react-router-dom@6 you should wrap the Route components in a required Routes component that handles the route path matching and rendering. The Route component API also changed a bit, there is now only a single element prop that takes a ReactNode, a.k.a. JSX, to render the routed content.

Example:

import React, { Component } from 'react';
import {
  BrowserRouter as Router,
  Routes,
  Route,
} from 'react-router-dom';
import HomePage from './pages/HomePage';
import './App.css';

class App extends Component {
  render() {
    return (
      <Router>
        <div className="App">
          <Routes>
            <Route path="/" element={<HomePage />} />
          </Routes>
        </div>
      </Router>
    );
  }
}

For a more complete guide of the differences between RRD v5 and v6 check the migration guide.

OFC, if you want to keep your existing code you could revert back to react-router-dom@5.

  • npm uninstall -s react-router-dom
  • npm install -s react-router-dom@5
  • Related