2

i am getting this error

uncaught Error: useNavigate() may be used only in the context of a <Router> component.
    at invariant (bundle.js:36570:20)
    at useNavigate (bundle.js:36914:35)
    at App (bundle.js:40:75)
    at renderWithHooks (bundle.js:23252:22)
    at mountIndeterminateComponent (bundle.js:26014:17)
    at beginWork (bundle.js:27213:20)
    at HTMLUnknownElement.callCallback (bundle.js:12202:18)
    at Object.invokeGuardedCallbackDev (bundle.js:12251:20)
    at invokeGuardedCallback (bundle.js:12311:35)
    at beginWork$1 (bundle.js:32053:11)

i have read may another answers from this website. like someone said put browser router in index.js.i tried it but its not working .it showing the same

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';


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

this is my main file app.js its a api project.i m using my navigate within a fuction. you can check my submit handle fuction.i put my navigate function inside a if condition.

import {React,useState} from 'react'
import { useEffect } from 'react';
import { BrowserRouter as Routes,Route } from 'react-router-dom';
import { useNavigate } from 'react-router';
import './index.css'
import Beta from './Main/Beta'
import Home from './Main/Home'
export default function App() {

  let navigate=useNavigate();

const submitHandle = (e)=>{ 
e.preventDefault();
setendpoint(keyword);
if(firstChange){
  navigate('/about');
}
}

  const [keyword, setkeyword] = useState('');
  const [endpoint, setendpoint] = useState('');
  const [answer, setanswer] = useState([]);
  const [isAnswerOk, SetIsAnswerOk] = useState(false);
  const [firstChange, setfirstChange] = useState(false);
  
  useEffect(() => {
  const options = {
    method: 'GET',
    headers: {
      'X-RapidAPI-Host': 'google-web-search.p.rapidapi.com',
      'X-RapidAPI-Key': 'f0892566b9mshc3d8dec8b959f05p1e24b6jsn38bfa46eacef'
    }
  };
  if (endpoint && endpoint.length>=1) {
    setfirstChange(true);
  fetch(`https://google-web-search.p.rapidapi.com/?query=+${endpoint}&gl=US&max=10`, options)
    .then(response => response.json())
    .then(data => {
      SetIsAnswerOk(true)
        setanswer(data.results)
      
     })
    .catch(err => console.error(err));
    
  }}, [endpoint])

const search =(e)=>{
setkeyword(e.target.value);
console.log(keyword);

}



  return (
    
   <div>
  
      <Routes>
      <Route path='/' element={<Home endpoint={endpoint}  search={search} keyword={keyword} response={submitHandle} />}/> 
      <Route path='/search' element={<Beta search={search} farma={answer} response={submitHandle} isAnswerOk={isAnswerOk} keyword={keyword}/>}/> 
      </Routes>
       </div>
   
    
    
    
  )
}






isherwood
  • 58,414
  • 16
  • 114
  • 157

2 Answers2

0

I think you are using the incorrect library for useNavigate. useNavigate is the part of 'react-router-dom'

import {useNavigate} from "react-router-dom"

Check the same thing on this link

Additionally as per the new update the Switch is replace with Routes which is the also the part of react-router-dom.

So you can use the router like below as per the information shared on this githib tutorial of react-router-dom - link.

const rootElement = document.getElementById("root");
render(
  <BrowserRouter>
    <Routes>
      <Route path="/" element={<App />} />
      <Route path="expenses" element={<Expenses />} />
      <Route path="invoices" element={<Invoices />} />
    </Routes>
  </BrowserRouter>,
  rootElement
);

Please let me know if this resolves your issue.

ttr
  • 11
  • 7
0

Issue

Wrapping App component with a router is correct if you want to use any react-router-dom hooks in the App component.

import React from 'react';
import { BrowserRouter } from 'react-router-dom';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

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

The issue now is that the App component is incorrectly importing another router and renaming it Routes.

import { BrowserRouter as Routes, Route } from 'react-router-dom';

Solution

Fix this import, just import Routes to correctly wrap all the Route components. react-router-dom also re-exports all of react-router so there's no need to import from react-router. In fact, you don't even need react-router as a package dependency because you've already included react-router-dom.

App

import { React, useEffect, useState } from 'react';
import { Routes, Route, useNavigate } from 'react-router-dom'; // <-- fix import
import './index.css';
import Beta from './Main/Beta';
import Home from './Main/Home';

export default function App() {
  const navigate = useNavigate();

  const submitHandle = (e) => { 
    e.preventDefault();
    setEndpoint(keyword);
    if (firstChange) {
      navigate('/about');
    }
  }

  const [keyword, setKeyword] = useState('');
  const [endpoint, setEndpoint] = useState('');
  const [answer, setAnswer] = useState([]);
  const [isAnswerOk, setIsAnswerOk] = useState(false);
  const [firstChange, setFirstChange] = useState(false);
  
  useEffect(() => {
    const options = {
      method: 'GET',
      headers: {
        'X-RapidAPI-Host': 'google-web-search.p.rapidapi.com',
        'X-RapidAPI-Key': 'f0892566b9mshc3d8dec8b959f05p1e24b6jsn38bfa46eacef'
      }
    };
    if (endpoint?.length >= 1) {
      setFirstChange(true);
      fetch(`https://google-web-search.p.rapidapi.com/?query=+${endpoint}&gl=US&max=10`, options)
        .then(response => response.json())
        .then(data => {
          setIsAnswerOk(true);
          setAnswer(data.results);
        })
        .catch(err => console.error(err));
    }
  }, [endpoint]);

  const search = (e) => {
    setKeyword(e.target.value);
  }

  return (
    <div>
      <Routes> // <-- use Routes, not any router, here
        <Route
          path='/'
          element={(
            <Home
              endpoint={endpoint}
              search={search}
              keyword={keyword}
              response={submitHandle}
            />
          )}
        /> 
        <Route
          path='/search'
          element={(
            <Beta
              search={search}
              farma={answer}
              response={submitHandle}
              isAnswerOk={isAnswerOk}
              keyword={keyword}
            />
          )}
        /> 
      </Routes>
    </div>
  );
};
Drew Reese
  • 165,259
  • 14
  • 153
  • 181