0

My navigation not working for some reason I have another app working fine but this one can't locate the error Please HELP

What did I do wrong? I followed all required steps

React Router not working. React JS

I need your HELP.

With react-router I can use the Link element to create links which are natively handled by react router.

It just keeps scrolling. I never opens the page

import './App.css';

import { CarsConsumer } from './components/Context';

import Car from './components/Car';
import CarsList from './components/CarsList';

import React, { Component } from 'react'

import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";

import Saved from './components/Saved';
import Help from './components/Help';
import Home from './components/Home';

export default class App extends Component {
  render() {
    return (<Router> 
      <div className="App">
        <header className="App-header">
        
                <nav>
                                <ul id='navUnorderedList'>
                                    <div id='leftNav'>
                                        <li>
                                            <Link to="/"> Home </Link>
                                        </li>
                                        <li>
                                            <Link to="/saved"> Saved </Link>
                                        </li>
                                    </div>
                                </ul>
                </nav>
                <Switch>
                        <Route path="/" component={ Home }>
                            
                        </Route>

                        <Route path="/saved" component={Saved}>

                        </Route>
                        
                        
                </Switch>
        

        <CarsList />
        </header>
      </div>
      </Router>
    )
  }
}

Natnael S
  • 15
  • 5
  • Can you clarify what you mean by "It just keeps scrolling. I never opens the page"? Your `Switch` will *always* match "/" path first and render the `Home` component. – Drew Reese Nov 19 '20 at 04:56

1 Answers1

1

Put exact in your Home Route

<Route path="/" exact component={ Home }>

Why putting exact make a difference ?

React router does partial matching, so /save partially matches home route path, so it would incorrectly return the home route again!

The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

Reference

CodeSandBox

mirsahib
  • 104
  • 1
  • 2
  • 8
  • 2
    Better solution is to reorder the paths so more specific paths are specified *before* less specific paths. – Drew Reese Nov 19 '20 at 06:57