Home > Mobile >  React router error "TypeError: Object(...) is not a function"
React router error "TypeError: Object(...) is not a function"

Time:11-15

im currently learning react. During course about routing i get this error Screenshoot I' ve been making sure that i' ve write code right and trying my best to find solution for around 3 hours now and i cant solve this for my own so i am seeking for help.

    import React from "react";
import "./index.css";
import { BrowserRouter, Route } from 'react-router-dom';
import TwittersView from '../TwittersView/TwittersView';
import ArticlesView from '../ArticlesView/ArticlesView';
import NotesView from '../NotesView/NotesView';

render() {
    return (
      <BrowserRouter>
        <>
          <h1>hello world</h1>
          <Route exact path="/" component={TwittersView} />
          <Route path="/articles" component={ArticlesView} />
          <Route path="/notes" component={NotesView} />
        </>
      </BrowserRouter>
    );
  }
}

export default Root;



  

CodePudding user response:

You need to wrap your <Route> component with <Routes> component.

And react-router-dom v5 and v6 has different syntax to render routes.

Here is the example with react-router-dom v6.

import React from "react";
import { BrowserRouter, Link, Route, Routes } from "react-router-dom";

const TwittersView = () => {
  return <h1>Twitter view</h1>;
};
const ArticlesView = () => {
  return <h1>Articles view</h1>;
};
const NotesView = () => {
  return <h1>Notes view</h1>;
};

const App = () => {
  return (
    <BrowserRouter>
      <Link to="/">TwittersView</Link> &nbsp;
      <Link to="/articles">ArticlesView</Link> &nbsp;
      <Link to="/notes">NotesView</Link>
      <Routes>
        <Route path="/" element={<TwittersView />} />
        <Route path="/articles" element={<ArticlesView />} />
        <Route path="/notes" element={<NotesView />} />
      </Routes>
    </BrowserRouter>
  );
};

export default App;

CodePudding user response:

the component is no longer in accord with the latest versions of react also I think Switch is not working now Routes has been replaced don't know why this doesn't reflect latest documentation.

import { BrowserRouter, Route, Routes } from 'react-router-dom';
.
.
.
 <BrowserRouter>
      //Navlink handeling here ie Navbar component with custom css


      <Routes>
        <Route path='/' element={<ElementName />}/>
        <Route path='/aboutus' element={<ElementName />}/>
      </Routes>
      
    </BrowserRouter>
  • Related