Changed syntax in react-route-dom from 'Switch' to 'Routes' but still no display in the browser

Viewed 84

I'm creating a Google Clone. This is my current code for that. I read that I needed to changed the syntax from 'Switch' to 'Routes', given the update for react-router. I did just that and my "This is the search page" is not displaying inside of the browser.

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


function App() {
  return (
    // BEM
    <div className="app">
      <Router>

        <Routes>
        <Route path="/search">
          <h1>This is the search page</h1>
        </Route>
        <Route path="/">
          <Home />
        </Route>
        </Routes>
      </Router>
    </div>
  );
}

export default App;
3 Answers

you need to create each component speratly some things like this:

 import React from 'react; 

function Home(){
     return(

       <div>
        <h1>Home</h1>
       </div>

           );
         }

  export default Home;




 import React from 'react; 
 function Search(){

   return(

    <div>
       <h1>Search</h1>
    </div>
  );

  }

  export default Search;

change index.js to :

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



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

change App.js to

 import React, {useEffect} from 'react';
 import ReactDOM from "react-dom";
 import { BrowserRouter ,Routes,Route} from 'react-router-dom';

 import Search from '.........'
 import Home from '.......' 


 function App(){
 return(
  <BrowserRouter>
    <Routes>
     <Route exact path="/" element={<Home/>} />
     <Route path="/search" element={<Search/>} />

     <Routes>


  </BrowserRouter>

  );

 }


 export default App;



 if(document.getElementById('app')){

  ReactDOM.render(<App/>,document.getElementById('app'));

 }

Route component expects 2 parameters path, and element.

Refer to the official doc here

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

In react-router-dom@6 the Routecomponent API changed significantly. Thechildrenprop is only used for rendering nestedRoutecomponents. All routed content is now rendered on a singleelementprop taking aReactNode`, a.k.a. JSX.

Move the content from being wrapped into the element prop.

function App() {
  return (
    // BEM
    <div className="app">
      <Router>
        <Routes>
          <Route path="/search" element={<h1>This is the search page</h1>} />
          <Route path="/" element={<Home />} />
        </Routes>
      </Router>
    </div>
  );
}
Related