6

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

1
  • 2
    that's because of the exact prop. <Route path='/' component={Home} exact /> should work for you Commented Apr 16, 2020 at 5:08

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.