ReactJS presents an issue where buttons on the navigation bar are not properly aligned

I am currently utilizing the navbar component from Bootstrap 5, and I've encountered a UI problem.

What is my current setup?

This is the existing structure of my navbar: https://i.sstatic.net/eETzd.png

What is my desired outcome?

I aim to have the navbar buttons (Login and Signup) aligned to the right edge.

import React from "react";
import { Link, useNavigate } from "react-router-dom";

const Navbar = (props) => {
  let navigate = useNavigate();

  const handleLogout = () => {
    localStorage.removeItem("token");
    console.log("hello");
    navigate("/login");
    props.showAlert("User Logged Out successfully!", "info");
    
  };

  return (
    <>
      <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
        <div className="container-fluid">
          <Link className="navbar-brand" to="/">
            Navbar
          </Link>
          <button
            className="navbar-toggler"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#navbarNav"
            aria-controls="navbarNav"
            aria-expanded="false"
            aria-label="Toggle navigation"
          >
            <span className="navbar-toggler-icon"></span>
          </button>
          <div className="collapse navbar-collapse" id="navbarNav">
            <ul className="navbar-nav">
              <li className="nav-item">
                <Link className="nav-link active" aria-current="page" to="/">
                  Home
                </Link>
              </li>
              <li className="nav-item">
                <Link className="nav-link" to="/about">
                  About
                </Link>
              </li>
            </ul>

            {!localStorage.getItem("token") ? (
              <form className="d-flex">
                <Link
                  className="btn btn-outline-success mx-2"
                  to="/signup"
                  role="button"
                >
                  SignUp
                </Link>
                <Link
                  className="btn btn-outline-success"
                  to="/login"
                  role="button"
                >
                  Login
                </Link>
              </form>
            ) : (
              <form className="d-flex">
                <button
                  className="btn btn-outline-success mx-2"
                  onClick={handleLogout}
                >
                  LogOut
                </button>
              </form>
            )}
          </div>
        </div>
      </nav>
    </>
  );
};

export default Navbar;

Despite several attempts and using built-in Bootstrap classes, I haven't been able to resolve this issue.

Answer №1

Simply include the me-auto class within the <ul> element like this:

<ul class="navbar-nav me-auto">

import React from "react";
import { Link, useNavigate } from "react-router-dom";

const Navbar = (props) => {
  let navigate = useNavigate();

  const handleLogout = () => {
    localStorage.removeItem("token");
    console.log("hello");
    navigate("/login");
    props.showAlert("User Logged Out successfully! ", "info");
    
  };

  return (
    <>
      <nav className="navbar navbar-expand-lg navbar-dark bg-dark">
        <div className="container-fluid">
          <Link className="navbar-brand" to="/">
            Navbar
          </Link>
          <button
            className="navbar-toggler"
            type="button"
            data-bs-toggle="collapse"
            data-bs-target="#navbarNav"
            aria-controls="navbarNav"
            aria-expanded="false"
            aria-label="Toggle navigation"
          >
            <span className="navbar-toggler-icon"></span>
          </button>
          <div className="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto"> 
              <li className="nav-item">
                <Link className="nav-link active" aria-current="page" to="/">
                  Home
                </Link>
              </li>
              <li className="nav-item">
                <Link className="nav-link" to="/about">
                  About
                </Link>
              </li>
            </ul>

            {!localStorage.getItem("token") ? (
              <form className="d-flex">
                <Link
                  className="btn btn-outline-success mx-2"
                  to="/signup"
                  role="button"
                >
                  SignUp
                </Link>
                <Link
                  className="btn btn-outline-success"
                  to="/login"
                  role="button"
                >
                  Login
                </Link>
              </form>
            ) : (
              <form className="d-flex">
                <button
                  className="btn btn-outline-success mx-2"
                  onClick={handleLogout}
                >
                  LogOut
                </button>
              </form>
            )}
          </div>
        </div>
      </nav>
    </>
  );
};

export default Navbar;

Answer №2

To achieve the desired result, simply insert me-auto within the <ul> tag as shown below:

<ul className="navbar-nav me-auto">

https://i.sstatic.net/Vlftn.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for accessing a URL with a specific value in the HTML file

This form submits a URL in this format: <form action="search.php?search=" method="GET" id="search-form"> <input id="search-text" name="search" type="text" maxlength="30" placeholder="type keyword"/> <button type="submit" name ...

Substitute a particular element within a text

I'm currently working on an Angular 9 application where I'm implementing search filters for the Shopify Graphql API. As part of this process, I am constructing a query which looks like: first: 1, query: "tag:'featured-1'", af ...

ExpressJS and cookies - Struggling to initialize a cookie with express-cookie

I recently followed a tutorial on YouTube (https://youtu.be/hNinO6-bDVM?t=2m33s) that demonstrated how to display a cookie in the developer tools Application tab by adding the following code snippet to the app.js file: var session = require('express- ...

Strategies for detecting changes in multiple HTML select elements with jQuery

I currently have three select HTML tags and I would like to filter my table using the selected values (group of selected tags) with an AJAX request. For example, filtering by Gender, Location, and Season. My question is how can I achieve this without dup ...

Safari's Web Audio API suffering from subpar performance and various shortcomings

For my University project, I am developing an HTML and JavaScript-based mp3 player using the Web Audio API. You can check out the progress of this project by visiting this link: While everything is running smoothly on Firefox and Chrome, Safari is posing ...

Introduction to Flask with GAE (blank Firefox tab)

Recently, I completed the Getting Started with Flask on App Engine Standard Environment tutorial. If you are interested, you can find the source code here. During my testing using Firefox and Chrome, I noticed that both browsers did not render the HTML te ...

Is it better to store CSS and JavaScript in separate files or within the main HTML document

While the best practice is to place JavaScript and CSS code in separate files (such as .js and .css), many popular websites like Amazon, Facebook, etc. often include a large portion of their JavaScript and CSS code directly within the main HTML page. Whic ...

Utilizing jQuery show() and hide() methods for form validation

I created a form to collect user details and attempted to validate it using the jQuery hide and show method. However, I seem to be making a mistake as the required functionality is not working correctly. What am I missing? I have searched for solutions on ...

retrieve the responseText in an ajax request

I am looking to receive Ajax feedback. var response = $.ajax({ url : 'linkAPI', type : 'get', dataType: 'JSON' }); console.log(response); Only the respo ...

Ways to deactivate a Material-UI submit button linked with Formik

Formik integration with Mui for a button component: import React from "react"; import { Button } from "@mui/material"; import { useFormikContext } from "formik"; const ButtonWrapper = ({ children, ...otherProps }) => { ...

React-navigation - Navigation causing premature triggering

Recently, I've started incorporating react-router into my application, and it's been working smoothly overall. However, there's a small hiccup that I've encountered. There's a scenario where I need to click on a button to navigate ...

Using JQuery to reverse the action of hiding an image

Having some trouble with my Javascript and JQuery skills, so bear with me. I've set up a gallery of images where users can drag and drop them into a designated drop zone. Everything works fine when dragging an image from the gallery to the drop zone a ...

Is it possible to customize the color of the placeholder and clear-icon in the ion-search bar without affecting

I am working with two ion-search bars and I need to customize the placeholder and clear icon color for just one of them. <ion-searchbar class="search-bar" placeholder="search"></ion-searchbar> My goal is to target a specific i ...

"Experience the new Bootstrap 5 feature: Off-Canvas sliding from left to

I encountered the code snippet below on the official bootstrap 5 demo. Despite my efforts, I am struggling to figure out how to relocate the off-canvas menu from Left-to-Right. The divergence between the documentation code referencing offcanvas-start and t ...

Remove the option to delete without making any changes to the flash file

Utilizing the DataTable javascript tool to export a grid, I have obtained the following HTML generated code: <div class="DTTT_container"> <a class="DTTT_button DTTT_button_copy" id="ToolTables_example_0" tabindex="0" aria-controls="e ...

Is there a way to showcase a block of Python code using a combination of HTML, CSS, and Javascript to enhance its

On my website, I want to display code blocks similar to how StackOverflow does it. The code block should be properly colored, formatted, and spaced out for better readability. All the code blocks on my site will be in python. def func(A): result = 0 ...

Leveraging the power of `.vue` files in modern web browsers that have native support for

Chrome 60 and the most recent version of Firefox, when used with certain flags enabled, have implemented support for import/export directives. I am interested in utilizing .vue files without relying on NodeJS, but I haven't been able to figure out how ...

jQuery is displaying fields inside the widget box that were supposed to have been removed

I am currently working on a project with a widget foldable box function called Metadata Widget. This widget displays certain fields, and I have added an import button to the side that calls upon the Metadata Widget and shows it. However, I have noticed tha ...

Is there a way to create a customized calendar in Node.js?

I am looking for a way to showcase a calendar in a localized format, not only in terms of language but also supporting non-Gregorian calendars such as Persian, Chinese, or Buddhist. In the past, when I worked with Java, I relied on ICU4J for this task. Ho ...

Is there a way to bring in a variable from the front end script?

Is it possible to transfer an array of data from one HTML file to another? If so, how can this be done? Consider the following scenario: First HTML file <script> let tmp = <%- result %>; let a = '' for (const i in tmp){ ...