Home > Back-end >  I'm facing this error in client side in React,js
I'm facing this error in client side in React,js

Time:06-01

index.js

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';

ReactDOM.render(<App />, document.querySelector('#root'));

App.js

import React from 'react';

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

import Join from './components/Join';
import Chat from './components/Chat';

const App = () => (
    <Routes>
        <Route path='/' exact component={Join} />
        <Route path='/chat' component={Chat} />
    </Routes>
);

export default App;

It thows error like "Error: useRoutes() may be used only in the context of a component."

Here is the ERROR: "

CodePudding user response:

You have to wrap your app in the BrowserRouter component in order to be able to use routing

So the code in index.js will be as follows

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';


import App from './App';

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

You could instead wrap the app in App.js

import React from 'react';

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

import Join from './components/Join';
import Chat from './components/Chat';

const App = () => (
  <BrowserRouter>
    <Routes>
        <Route path='/' exact component={Join} />
        <Route path='/chat' component={Chat} />
    </Routes>
   </BrowserRouter>
  );
    export default App;

but for cleaner code, do the first approach

CodePudding user response:

Wrap your code inside <BrowserRouter> making sure it isn’t in the app itself but higher up in the tree.

  • Related