1

I am new to React Router and I am encountering some strange behavior. I am currently using React Router 5.2.0. I have created a simple navigation link that links to the component. The links update fine, but it doesn't render the component for the appropriate route. It only renders the component only after I refresh the page. In this example, it would be for the Music component and the Languages component.

Here is my navigation.js:

import React from 'react';
import {NavLink} from 'react-router-dom';

export const Navigation = () =>{

    return(
        <ul className = "navList">
            <li className = "listItem">Programming</li>
            <li className = "listItem">Exercise</li>
            <li className = "listItem"><NavLink to = "/music">Music</NavLink></li>
            <li className = "listItem"><NavLink to = "/languages">Languages</NavLink></li>
            <li className = "listItem">Travel</li>
            <li className = "listItem">Inspiration</li>
        </ul>

    )
}

and here is my app.js file:

import './App.css';
import React from 'react';
import {Navigation} from './Components/navigation';
import {Music} from './Components/music';
import {Languages} from './Components/languages';

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

function App() {

  return (
    <Router>
      <>
    <header className = 'header'>
        Life
      <Navigation/>
    </header>
      <Route path = "/music">
        <Music/>
      </Route>
      <Route path = "/languages">
        <Languages/>
      </Route>
    </>
    </Router>
  )
}

export default App;

Any ideas why this is happening? I'm not sure what I am doing wrong. Am I using <Router> or <Route> in the correct manner? Any help is appreciated. Take care!

Drew Reese
  • 165,259
  • 14
  • 153
  • 181
vroque2022
  • 23
  • 4
  • 1
    You havn't wrapped your `Route`s in a `Switch`. – super Jul 31 '22 at 20:42
  • 1
    What version of `react` are you using? If you are using React 18 does this help answer your question? https://stackoverflow.com/a/71833424/8690857 – Drew Reese Jul 31 '22 at 20:46
  • @super The `Switch` component isn't required to wrap routes, and since there's zero ambiguity between the two route paths there isn't much need for it either. – Drew Reese Jul 31 '22 at 20:47
  • 1
    @DrewReese thank you so much!! This solved the issue. Yes I was using React 18 and I didn't know there were compatibility issues with React 18 and versions of react router before 5.3.3. I just installed react router version 5.3.3 as was outlined in the post you sent me. Thanks again :) – vroque2022 Jul 31 '22 at 22:53

0 Answers0