Home > OS >  useLocation() may be used only in the context of a <Router> component
useLocation() may be used only in the context of a <Router> component

Time:04-15

Okay, I know this is a question that other people have already asked, but none of their answers are helping me.

I have a react application that has a Navbar component. One of the items of that Navbar component is another component named Products, that's where I get the error.

import React, {useState, useEffect} from 'react';
import { Container, Row, Col } from 'react-grid-system';
import { useLocation } from 'react-router';
import { BrowserRouter } from 'react-router-dom';
import NavbarHome from './NavbarHome';


function Products() {

  const [products, setProducts] = useState([]);
  useEffect(() => {
    const getProducts = async ()=>{
      const res = await fetch('http://localhost:3001/products');
      const getData = await res.json();
      setProducts(getData);
    }
    getProducts();
  },[]);

  **let location = useLocation();
  console.log(location);**
    
  return (
    <div>
      <BrowserRouter>
        <NavbarHome />
        <Container className="products">
          <Row>
            {
              productos.map( (getProducts) => (
                  <Col sm={4}>
                    <div className='producto'>
                        key={getProductos.idproduct}
                        {/*<img src={`${getProductos.image}`}></img>*/}
                        <p>{getProductos.name}</p>
                        <p>{getProductos.price} $</p>
                    </div>
                  </Col>
                
                )
              )
            }
          </Row>
      </Container>
    </BrowserRouter>
     
    </div>
  );
}

export default Productos;

The solution that everybody gives is to wrap the block of code in a Router, but it is not working for me. Any ideas?

Thank you so much in advance!

CodePudding user response:

Have you tried changing the useLocation import from react-router to react-router-dom?

  • Related