Payne
Payne

Reputation: 543

Pages are not redirected on menu click, only changes in URL - ReactJs

In my App.js, I have the following code snippet. All I want to achieve is to able to click on the link to home or about and have the page rendered.

import React from 'react';
import logo from './logo.svg';
import './App.css';
import Home from './components/Home';
import Header from './components/Header';
import About from './components/About';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'

function App() {
  return (
    <Router>
    <div className="App">
      <Switch>
        
        <Route path="/" component={Home}>
          <Header />
          <Home />
        </Route>
        <Route path="/about" component={About}>
            
            <About />
        </Route>
       
      </Switch>
    </div>
    </Router>
  );
}

export default App;

In my Header.js When I click on the About links, the change appears only on URL but no page is rendered, it remains in default page.

import React from 'react'
import { Link } from 'react-router-dom'


function Header() {
   
    return (
        <div>
            <ul>
                <li><Link to="/" >Home</Link></li>
                <li><Link to="/about">About</Link></li>
            </ul>
        </div>
    )
}

export default Header

I have similar content for the home and about function with the h1 tag captioned differently.

import React from 'react'

function Home() {
    return (
        <div>
           <h1> Home </h1>
        </div>
    )
}

export default Home

About.js

import React from 'react'

function About() {
    return (
        <div>
            <h1>About </h1>
        </div>
    )
}

export default About

I don't know if there is anything else I need to do.

Upvotes: 1

Views: 259

Answers (1)

Abdulkabir Ojulari
Abdulkabir Ojulari

Reputation: 1467

Your code is perfectly in order, just need to reposition the Route, ensure the default route is listed below as follow:

 <Router>
    <div className="App">
      <Switch>
      <Route path="/about" >
            <Header />
            <About />
        </Route>
        <Route path="/">
          <Header />
          <Home />
        </Route>
        
       
      </Switch>
    </div>
    </Router>

"react-router-dom" documentation needs to point this to the reader.

Upvotes: 1

Related Questions