Search code examples
javascriptreactjsrenderingclass-names

Conditionally render a badge for active/inactive User


I am trying to render conditionally a badge, based on the logged condition of a user. If the props coming from the server is true, then the badge is green, else grey.

I have tried various solutions, from basic if/else in the JSX, to classNames but the badge isn't being render.

My Code:

              {user.loggedIn ? (
                <div
                  className={classNames('badge badge-pill', {
                    'badge-success': user.loggedIn,
                    'badge-danger': !user.loggedIn
                  })}
                />

I don't see anything wrong with the code. I mean the item should have rendered, with multiple solutions. Any ideas, what I am doing wrong.

              <span
                className={
                  user.loggedIn ? 'badge badge-pill badge-success' : 'badge badge-pill badge-muted'
                }
              />

I have tried this as well.

I can see the element in the React-Dev-Tools, being render correctly, witht the right prop, but I cannot see it render in the screen.


Solution

  • Your contents will only get rendered if user is loggedIn. Also the div tag must be closed inside the condition { isLoggedIn }

    you should try something like this:

            {user.loggedIn ? (
          <div className={'badge badge-pill badge-success'}>ENTER YOUR CONTENT HERE</div>) : (
                <div className={'badge badge-pill badge-danger'}>ENTER YOUR CONTENT HERE</div>
        )}
    

    but since the div is self-closing and has no contents, it doesn't display it, so add some content too