36

im facing Uncaught TypeError: Cannot destructure property 'basename' of 'React2.useContext(...)' as it is null. in the link component of the code

import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';

import { styles } from '../styles';
import { navLinks } from '../constansts';
import { logo, menu, close } from '../assets';

const Navbar = () => {
  const [active, setActive] = useState('');
  return (
    <nav className={`${styles.paddingX} w-full flex items-center py-5 fixed top-0 z-20     bg-primary`}>
      <div className="w-full flex justify-between items-center max-w-7x1 max-auto">
        <Link
          to="/"
          className="flex items-center gap-2"
          onClick={() => {
            setActive('');
            window.scrollTo(0, 0);
          }}
        >
          <img alt="logo" />
        </Link>
      </div>
    </nav>
  );
};

export default Navbar;

i have no idea how to fix it can anyone tell me how to fix it please

Ali Nauman
  • 1,374
  • 1
  • 7
  • 14
Subham Negi
  • 371
  • 1
  • 3
  • 6
  • where you are using the useContext() hook? – MagnusEffect Mar 14 '23 at 05:30
  • move this Nav component to be within the ``, before `` tag. I just couldn't find yet the reason why the Link component must be within BrowserRouter, maybe it is the only way react can handle the page navigation and switch one at a time. – Junior Mayhé Mar 14 '23 at 21:11

2 Answers2

86

You're using Link from react-router-dom but your app is not wrapped by a BrowserRouter. Your index.js:

import { BrowserRouter } from 'react-router-dom'

render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById('root')
)
Arthur
  • 2,622
  • 4
  • 28
  • 46
2

Be sure to use routing properly on App.js and put the navbar component inside the BrowserRouter. As an example let's pretend that your app.js looks similar to:

function App() {
  return (
  <div className="App">
    
    <Router>
      <Routes>
        <Route path="/" element={<HomePage/>}/>
        <Route path="/x" element={<x/>}/>
        <Route path="/y" element={<y/>}/>
        <Route path="/z" element={<z/>}/>
        <Route path="/*" element={<NotFound/>}/>
      </Routes>
    </Router>
  </div>);
}

export default App;

then:

 function App() {
  return (
  <div className="App">
    
    <Router>
      <Routes>
        <NavBar/>
        <Route path="/" element={<HomePage/>}/>
        <Route path="/x" element={<x/>}/>
        <Route path="/y" element={<y/>}/>
        <Route path="/z" element={<z/>}/>
        <Route path="/*" element={<NotFound/>}/>
      </Routes>
    </Router>
  </div>);
}

export default App;

Be sure to also add the import!

edit: before wrapping the routes, I imported BrowserRouter as Router because it helps me to understand the code, that's why it's declared like that