UrTech Tips
UrTech Tips

Reputation: 69

React-Router dose not work while using BrowserRouter after Build

So i have a app which is using React-Router BrowserRouter to navigate between different components

Code:

return (
    <Router>
        <div className="container">
            <Navbar logged={loggedIn} />

            <Switch>
                <Route path="/" exact>
                    <Welcome />
                </Route>
                <Route path="/logout" exact>
                    <Logout loggedSet={setLoggedIn} logged={loggedIn} />
                </Route>
                <Route path="/login" exact>
                    <Login onLogin={login} loggedIn={loggedIn} />
                </Route>
                <Route path="/dashboard" exact>
                    {loggedIn ? <Dashboard /> : <Redirect to="/" />}
                </Route>
                <Route path="/add" exact>
                    {loggedIn ? <Add /> : <Redirect to="/" />}
                    <Add />
                </Route>
            </Switch>
        </div>
    </Router>
);

When i build this this shows a Blank Page i got to know to add "homepage": ".", in package.json . I did so and not it shows Navbar Component but it dosent show any components which are under I searched and found we need to use HashRouter. is using hashrouter correct if so how to change my code to use hashrouter.

Thankyou

Upvotes: 1

Views: 294

Answers (2)

T J
T J

Reputation: 43166

You should put the generic route last, without the exact as shown below. Otherwise it'll only show up if your are exactly at root /, any hashes, query params etc will cause it to not match and your app will not show anything:

<Switch>
    <Route path="/logout" exact>
        <Logout loggedSet={setLoggedIn} logged={loggedIn} />
    </Route>
    <Route path="/login" exact>
        <Login onLogin={login} loggedIn={loggedIn} />
    </Route>
    <Route path="/dashboard" exact>
        {loggedIn ? <Dashboard /> : <Redirect to="/" />}
    </Route>
    <Route path="/add" exact>
        {loggedIn ? <Add /> : <Redirect to="/" />}
        <Add />
    </Route>
    <Route path="/">
        <Welcome />
     </Route>
 </Switch>

Upvotes: 2

you are putting the build in a subfolder?. If yes check this: React Router with relative path deployment

and this React-router app deployed on different locations (subdirectories)

Upvotes: 1

Related Questions