How to redirect to dashboard based on user roles in ReactJS

Viewed 45

I have two components 1 is adminRoutes which displays admindashboard and the other is Userdashboard which shows userDashboard, below are screenshots of admin and user dashboards

user dashboard, admin dashboard

What I did here is after successfull login i navigate to ("/") which returns <Home/> component that is my admin dashboard. Below is the code of login. When login button is clicked, the useEffect is fired.

useEffect(() => {
    if (Object.keys(formErrors).length === 0 && isSubmit) {
        signInWithEmailAndPassword(auth, UserLogin.email, UserLogin.password)
            .then((userCredential) => {
                // Signed in 
                const user = userCredential.user
                const docRef = doc(db, 'admin', user.uid)
                getDoc((docRef)).then((doc) => {
                    localStorage.setItem('currentuser', JSON.stringify(doc.data()));
                });
                dispatch({
                    type: "LOGIN",
                    payload: user
                })
                navigate("/user/");
            })
            .catch((error) => {
                setError(error);
                setInterval(() => {
                    setError();
                }, 4000)
            });
    }
}, [formErrors])

Here I am saving my currentUser from firebase to localStorage, user object has properties email, id, name, role and based on the role I want to switch admindashboard or userdashboard while I am logging in.

Here is the main App component code

function App (){
    return (
        <>
            <UserRoutes/>
        </>
    )
}

export default App;

And below is AdminRoutes component that has different routes for admindashboard pages

import { BrowserRouter as Router, Routes, Route, Navigate } from "react-router-dom";
import UserDashboard from "../../UserDashBoard/UserDashboard";

export default function AdminRoutes() {
    const { currentUser } = useContext(AuthContext);
    const RequireAuth = ({ children }) => {
        return currentUser ? children : <Navigate to={"/Login"} />;
    };

    return (
        <>
            <Router>
                <Routes>
                    <Route path="/">
                        <Route path="Login" element={<Login />} />
                        <Route path="Signup" element={<Signup />} />
                        <Route
                            index
                            element={
                                <RequireAuth>
                                    <Home />
                                </RequireAuth>
                            }
                        />
                        <Route path="user">
                            <Route
                                index
                                element={
                                    <RequireAuth>
                                        <UserList />
                                    </RequireAuth>
                                }
                            />
                            <Route
                                path=":userid"
                                element={
                                    <RequireAuth>
                                        <User />
                                    </RequireAuth>
                                }
                            />
                        </Route>
                        <Route path="documents">
                            <Route
                                index
                                element={
                                    <RequireAuth>
                                        <Document />
                                    </RequireAuth>
                                }
                            />
                        </Route>
                        <Route path="createcategory">
                            <Route
                                index
                                element={
                                    <RequireAuth>
                                        <CreateCategory />
                                    </RequireAuth>
                                }
                            />
                        </Route>
                        <Route path="viewuser">
                            <Route
                                index
                                element={
                                    <RequireAuth>
                                        <UserList />
                                    </RequireAuth>
                                }
                            />
                        </Route>
                        <Route path="uploaddoc">
                            <Route
                                index
                                element={
                                    <RequireAuth>
                                        <Upload />
                                    </RequireAuth>
                                }
                            />
                        </Route>
                        <Route path="createuser">
                            <Route
                                index
                                element={
                                    <RequireAuth>
                                        <CreateUser />
                                    </RequireAuth>
                                }
                            />
                        </Route>
                        <Route path="Viewdocuments">
                            <Route
                                index
                                element={
                                    <RequireAuth>
                                        <Document />
                                    </RequireAuth>
                                }
                            />
                        </Route>
                    </Route>
                </Routes>
            </Router>
        </>
    );
}

Based on Roles I want to show Dashboard. If admin logged in show admin dashboard, if user logged in show userdashboard. How can I achieve it? I am still learning reactjs. Thank You.

1 Answers

Edit after clarifying what OP wants to achieve: You need to add context and then make routing based on data in it.

// in the App.js, wrap your components with Context so it is accessible
function App (){
    return (
        <AuthContext.Provider>
            <UserRoutes/>
        </AuthContext.Provider>
    )
}

export default App;

In component UserRoutes:

const { currentUser } = useContext(AuthContext);
const RequireAuth = ({ children }) => {
    return currentUser ? children : <Navigate to={"/Login"} />;
};

if (currentUser.role === "admin") return ( { /* user is admin, return routes for admin */ }
    <Router>
        <Routes>
            { /* all the routes for user admin, ex. */ }
            <Route path="admindashboard" element={<AdminDashboard />} />
        </Routes>
    </Router>
)

return ( { /* user is regular user, return routes for user */ }
    <Router>
        <Routes>
            { /* all the routes for user, ex. */ }
            <Route path="user-dashboard" element={<UserDashboard />} />
        </Routes>
    </Router>
)
Related