skip to Main Content

I want to render user name in the navbar if the user is logged in. If I use Normal Text inside h1, like User I get that in the browser but when I’m using {user.name} it’s not getting me the name of user from database.

I have tried like this

import React from "react";

function Navbar() {
    const user = JSON.parse(localStorage.getItem("currentUser"));
    return (
        <div>
            <nav class="navbar navbar-expand-lg">
                <a class="navbar-brand" href="#">
                Book Rooms
                </a>
                <button
                class="navbar-toggler"
                type="button"
                data-toggle="collapse"
                data-target="#navbarNav"
                aria-controls="navbarNav"
                aria-expanded="false"
                aria-label="Toggle navigation"
                >
                    <span class="navbar-toggler-icon"></span>
                </button>
                <div class="collapse navbar-collapse" id="navbarNav">
                    <ul class="navbar-nav">
                        {user ? (
                        <>
                            <h1 style={{color: 'white'}}>user</h1> 
                        </>
                        ) : (
                        <>
                            <li class="nav-item active">
                            <a class="nav-link" href="/register">
                                Register
                            </a>
                            </li>
                            <li class="nav-item">
                            <a class="nav-link" href="/login">
                                Login
                            </a>
                            </li>
                        </>
                        )}
                    </ul>
                </div>
            </nav>
        </div>
    );
}

export default Navbar;

2

Answers


  1. Try updating your <h1> tag to

    <h1 style={{color: 'white'}}>{user.name}</h1>
    
    Login or Signup to reply.
  2. First make sure to console.log the user before component rendering to confirm that the user object is present in the localStorage :

    const user = JSON.parse(localStorage.getItem("currentUser"));
    console.log(user);
    

    if you get a good looking result in the console then procede to use in in any part of the rendered component like so
    {user}
    for example:

     return (
    ....
    ..
    .
    <h1 style={{color: 'white'}}>USERNAME: {user.name}</h1>
    ...
    ..
    .
    )
    

    at this point if you cannot see the element on screen it’s most likely due to bad css, perhaps the element is out of screen or hidden. From the ChromeDevtools Inspect panel search for USERNAME (given that you used my example from the previous line) and use the mouse to highlight where is the h1 located; fix the CSS accordingly.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search