How to show a default view in React?

Viewed 391

I have a React site with three different routes, and I want it to automatically display the first one, which is called Home, when a user enters the site. Here is the code I have in App.js:

<Router>
  <Navigation />
  <Switch>
    <Route path="/hypstats" exact component={() => <Home />} />
    <Route path="/hypstats/auctions" exact component={() => <AuctionViewer />} />
    <Route path="/hypstats/bazaar" exact component={() => <BazaarViewer />} />
  </Switch>
</Router>

And here is the Navigation component:

import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import "../App.css"

function Navigation(props) {
    return (
        <div className="navbar">
            <Link className="navlink" to="/hypstats">HypStats</Link> 
            <Link className="navlink" to="/hypstats/auctions">Auctions</Link>
            <Link className="navlink" to="/hypstats/bazaar">Bazaar</Link>
        </div>
    )
}

export default Navigation;
3 Answers

To make any view as the default view you could include the following into your Navigation

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

Or you could write as below:

<Redirect from="/" to="/hypstats"}  />


<Router>
    <Navigation />
        <Switch>
            <Route path="/hypstats" exact component={() => <Home />} />
            <Route path="/hypstats/auctions" exact component={() => <AuctionViewer />} />
            <Route path="/hypstats/bazaar" exact component={() => <BazaarViewer />} />
            **<Route path="/" exact component={() => <Home />} />**
        </Switch>
</Router>

We use the basename attribute to tell the basename of the site. So that in the next routes, we would not have to set basename, here /hypstats, manually every time we add a new route. React Router manages it by itself.

<Router basename="/hypstats">
  <Navigation />
  <Switch>
    <Route path="/" exact component={() => <Home />} />
    <Route path="/auctions" exact component={() => <AuctionViewer />} />
    <Route path="/bazaar" exact component={() => <BazaarViewer />} />
  </Switch>
</Router>

Run this somewhere in your App component.

history.push({
 pathname: '/hypstats',
});

You are using "react-router-dom" so you can import:

import { useHistory } from "react-router-dom";

And then you can use:

const history = useHistory();

So whenever user enters your react application it will open the '/hypstats'.

You could do this in a useEffect.

Related