Maifee Ul Asad
Maifee Ul Asad

Reputation: 4607

react.js set default route

I have this piece of code in my index.js :

const routing = (
<Router>
    <Switch>
        <Route exact path="/">
            <Redirect to="/a" />
        </Route>
        <Route path="/a" component={A} />
        <Route path="/b" component={B} />
        <Route path="/c" component={C} />
    </Switch>
</Router>
)

It directly lands on /a and I can go to /b and /c too.

If I try to go to '/something' it renders nothing, as component for that path is not defined.

What I want to achieve is, I don't want to give access to '/something', although it gives nothing, renders nothing. I want if someone try to access '/something', he will automatically be redirected to '/default'.

Is it possible ?

Upvotes: 0

Views: 541

Answers (2)

Yes, that is the purpose of the <Switch>. A Switch will render exactly one of it's child nodes. You can do this:

const routing = (
<Router>
    <Switch>
        <Route exact path="/">
            <Redirect to="/a" />
        </Route>
        <Route path="/a" component={A} />
        <Route path="/b" component={B} />
        <Route path="/c" component={C} />
        <Route render={
            ()=>(<Redirect to="/a"/>)}
        />
    </Switch>
</Router>
)

The last route has no path so it will match every url. However, because of the switch if any of the other routes match it won't be rendered.

Upvotes: 5

MaartenDev
MaartenDev

Reputation: 5802

A wildcard can be used to match any route, checkout the following example:

const routing = (
    <Router>
        <Switch>
            <Route exact path="/">
                <Redirect to="/a"/>
            </Route>
            <Route exact path="/a" component={A}/>
            <Route exact path="/b" component={B}/>
            <Route exact path="/c" component={C}/>

            <Route path="*">
                <Redirect to="/a"/>
            </Route>
        </Switch>
    </Router>
)

Upvotes: 2

Related Questions