DEV Community

Velcruza
Velcruza

Posted on

How to display different components based on user authentication

Hey there! Ever want to display different components based on whether or not your user is logged in? Well, you're in the right spot. Let's dive right in.

To start off, you're going to want your two different components that you'll be displaying based on user authentication. For this example the two components I'm using are <LoggedOut/> and <LoggedIn/>. Next step is we need a route on the backend to render current user info. For this example the route I used is /me and heres what that looks like in my user controller:

def me
        if current_user
            render json: current_user, status: :ok
        else
            render json: {error: "Not logged in"}, status: :unauthorized
        end
    end
Enter fullscreen mode Exit fullscreen mode

From here, what we're going to be doing is fetching to this route /me to find out if our user is logged in, and if our user is logged in we're going set our current user to that and render our page based on that. That probably didn't make much sense but lets step through the code together.
In our App.js here is what we do:
We're starting off by setting 2 states

const [currentUser, setCurrentUser] = useState(null);
Enter fullscreen mode Exit fullscreen mode

Now we're going to fetch to our /me route to figure out if our user is logged in or not, and based on that info: if the user logged in we're setting our current user to that data, and if not then our current user remains null:

useEffect(() => {
    fetch("/me", {
      credentials: "include",
    }).then((res) => {
      if (res.ok) {
        res.json().then((user) => {
          setCurrentUser(user);
        });
      }
    });
  }, []);
Enter fullscreen mode Exit fullscreen mode

then in our return() we're going to dynamically render the elements based on if currentUser is a truthy value or a falsey value:

return (
      <>
        {currentUser ? (<LoggedIn/>) : (<LoggedOut/>)}
      </>
  );
Enter fullscreen mode Exit fullscreen mode

and that's all you need!

You can change the names for LoggedIn and LoggedOut to be whatever components you want to render based on if you're user is logged in or not. I hope this helped you out in any way and appreciate you following to the end!

Latest comments (0)