Home > Software design >  One router work but other router not work
One router work but other router not work

Time:01-01

Hey i have a reactjs app with this as app.tsx

    import tw from 'twin.macro';
    import { hot } from 'react-hot-loader/root';
    import { Route, BrowserRouter as Router, Routes as Switch } from 'react-router-dom';
    import Main from './Main';
    import Test from './Test';

    const App = () => {
        return (
            <><Main /><div css={tw`mx-auto w-auto`}>
                <Router>
                    <Switch>
                    <Route path="/element" element={<Test />} />
                    <Route path="/" element={<Main />} />
                    </Switch>
                </Router>
            </div></>
        );

    };

    export default hot(App);

But when i run a ./node_modules/.bin/webpack --watch --progress the localhost/ work but localhost/element not work i have a 404 error Not Found The requested URL was not found on this server Can you tell me why its not work?

(i use 6.2.1 of react-router-dom)

CodePudding user response:

I think you're using ‘react-router-dom’ newer version. Switch is no longer in the new version. please read here Switch' is not exported from 'react-router-dom'

CodePudding user response:

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

function App() {

  const Main = () => {
    return (
      <h1>Main</h1>
    )
  } 
  
  const Test = <h1>Test</h1>

  return (
    <div >
        <Router>
            <Switch>
                <Route path="/element" element={<Main />} />
                <Route path="/" element={Test} />
            </Switch>
        </Router>
    

    </div>
  );
}

export default App;

You need to use the <Main /> structure

CodePudding user response:

first and foremost you need to mention the version you are using , and try this if it works for u :-

in your code : import { Route, BrowserRouter as Router, Routes as Switch } from 'react-router-dom'; you are import Routes as Switch instead of Switch as Routes

your components should look like this, to work:-

import tw from 'twin.macro';
    import { hot } from 'react-hot-loader/root';
    import { Route, BrowserRouter as Router, Switch as Routes} from 'react-router-dom';
    import Main from './Main';
    import Test from './Test';

    const App = () => {
        return (
            <><Main /><div css={tw`mx-auto w-auto`}>
                <Router>
                    <Routes>
                        <Route exact  path="/element" element={Test} />
                        <Route exact  path="/" element={Main} />
                    </Routes>
                </Router>
            </div></>
        );

    };

NB: try to wrap your index.tsx component with the <BrowserRouter> </BrowserRouter> like this :

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

therefore you can remove the BrowserRouter from the app.tsx

  • Related