Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Router not routing correctly

I have the following:

import React, { Component } from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import Header from './layout/Header';
import Home from '../pages/Home';
import AboutUs from '../pages/Aboutus'
import { Layout } from 'antd';

class Main extends Component {

    render() {
        return (
        <Layout className="layout">
            <Header />
            <Switch>
                <Route path='/' component={Home} />
                <Route path='/about' component={AboutUs} />
                <Redirect to='/' />
            </Switch>
        </Layout>)
    };
}

export default Main;

When visiting / then Home is correctly loaded. When visiting a non-existing route then Home is loaded again but when visiting /about Home is loaded instead of AboutUs.

What's weird is that if I move AboutUs component to be loaded when visiting / instead of loading Home then AboutUs works well

like image 892
HerbertRedford Avatar asked Apr 16 '20 05:04

HerbertRedford


1 Answers

You need to use the exact prop, because “/“ match any route that starts with “/“, which is basically everything. https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/Route.md#exact-bool

like image 186
maten Avatar answered Sep 28 '22 04:09

maten