What is the best way to position this dropdown menu component directly under a specific section of my navbar in a React application?

As I delved into creating a basic navbar and dropdown menu in React, I encountered a puzzling issue. I envisioned a section within the nav that would trigger a dropdown menu right below it upon hovering over it. Attempting to replicate this functionality by copying code from the w3 site led to more complications than anticipated. Consequently, I decided to embark on my own approach...

The solution involved crafting a Dropdown functional component embedded within the Navbar component. The visibility toggling of the Dropdown is orchestrated using a useState variable named hideDropdown.

Thus far, everything seems to be operating smoothly. Nonetheless, trouble reared its head when trying to align the Dropdown underneath the account segment in the Navbar. Despite various attempts, achieving the desired position on screen becomes elusive. Even specifying the pixel count for the component's left offset statically proves futile—resizing the screen disrupts the alignment. Perplexingly, the Dropdown materializes on the left side by default, with only the left property demonstrating any noticeable impact on positioning. Right appears ineffectual while percentages appear disassociated from page width; setting the left property to 800% is necessitated to situate the Dropdown completely on the right side.

Refer here for the code snippet

Navbar.js

Beloved Readers,
I am currently immersing myself in web development and deriving immense pleasure from it. However, this particular task has become somewhat vexing as I perceive it as a relatively straightforward challenge. Any guidance extended my way would be greatly appreciated!

Warm regards,
Neophyte Developer

Answer №1

Here is the solution that I believe meets your requirements:

I made some adjustments to the CSS and JS code

CSS

.navinator {
  z-index: 1;
  list-style-type: none;
  margin: 0;
  padding: 0;
  background-color: rgb(218, 10, 10);
  position: fixed;
  top: 0;
  width: 100%;
  height: 47px;
}
.navElement {
  float: left;
}
.anchor{
  display: block;
  color: white !important;
  text-align: center;
  padding: 14px 16px; 
  text-decoration: none !important;
  cursor: pointer;
}
.anchor:hover {
  background-color: rgb(255, 23, 15) !important;
}
.active {
  background-color: rgb(28, 13, 110) !important;
  float: right;
  width: 120px;
}
.active .anchor{
  align-items: center;
  justify-content: center;
}
.active .anchor:hover {
  background-color: rgb(32, 11, 156) !important;
}
.profile-image {
  width: 30px;
  height: 30px;
  position: relative;
  overflow: hidden;
  border-radius: 50%;
}
#profile {
  color: white !important;
  text-align: center;
  padding: 11px 16px; 
  text-decoration: none !important;
  /* height: 52px; */
  overflow: auto;
}
#profile:hover {
  background-color: rgb(255, 23, 15) !important;
  cursor: pointer;
}
.arrow-down {
  width: 0;
  height: 0;
  border-left: 5px solid transparent;
  border-right: 5px solid transparent;
  border-top: 5px solid white;
  margin-top: 10px;
}
.dropdown {
  opacity:0;
  visibility: hidden;
    top: 47px;
    width: 222px;
    box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
    /* display: inline-block; */
    background-color: rgb(6, 6, 6);
    position: absolute;
}
.drop-item:hover .dropdown{
  opacity:1;
  visibility: visible;
  transition: all .3s;
}

.dropdown li{
  list-style-type: none;
}

JS

const Navbar = () => (
  <div style={{ zIndex: "1", position: "fixed", display: "flex" }}>
        <ul className="navinator">
          <li className="navElement">
            <a className="anchor" href="/home">
              Home
            </a>
          </li>
          <li className="navElement">
            <a className="anchor" href="/profile">
              Profile
            </a>
          </li>
          <li className="active">
            <a
              className="anchor"
              // href="#"

            >
              + New Post
            </a>
          </li>
          <li class="drop-item" style={{ float: "right" }}>
            <div
              id="profile"
              >
              <div style={{ float: "left", paddingRight: "10px" }}>
                <img
                  src=""
                  alt="error"
                  className="profile-image"
                />

              </div>
              <div style={{ float: "left", paddingRight: "5px" }}>
                whatever
              </div>
              <div style={{ float: "left" }} className="arrow-down"></div>
            </div>
            <div style={{float:"right"}} className="dropdown">

     <li>
        <a className="anchor" style={{ textAlign: "left" }} href="/profile">
          Profile
        </a>
      </li>
      <li>
        <a className="anchor" style={{ textAlign: "left" }} href="/profile">
          Profile
        </a>
      </li>

    </div>
          </li>
        </ul>

      </div>
)

ReactDOM.render(<Navbar />, document.getElementById('root'))

The issue solved involves displaying a dropdown menu upon hovering over an element in the navigation bar, positioning it below the parent element appropriately

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

Alert: validateDOMNesting() has detected that <p> is not allowed to be a child of <p> element

I have a React application with Material-UI (MUI). It consists of two main pages, Login and Signup. Both of these pages are wrapped in a top-level component: function TabPanel(props) { const { children, value, index, ...other } = props; return ( ...

CSS division style not being properly implemented across entire form

I currently have an HTML form linked to a CSS file. Here is the HTML code: .css-form-group{ margin-bottom:10px; clear:both; } .css-form-group label{ font-weight: bold; } .form-input{ float: right; } .form-input:focus{ background: y ...

Tips on ensuring the first column of an HTML table remains fixed in responsive design

I am trying to create a responsive HTML table where the first column remains fixed. I have a select box on my PHP page and I am using AJAX to display data from a database in the HTML table. However, when selecting a value in the select box in a responsiv ...

Confirm the data within an HTML table and apply color coding to the cells appropriately

Currently, I have an HTML table used to automatically validate data collected from soil pollutants analyses. Here is a snippet describing the table structure: <table id="table1"> <thead class="fixedHeader"> <tr><input type="submit" ...

Is there a way to deactivate the spin buttons for an input number field?

Is there a way to create an input element with type number in Vue using createElement() in TypeScript and then disable the spin buttons for increment and decrement? I attempted to use the following CSS: input[type=number]::-webkit-inner-spin-button, input ...

PHP - The form page freezes up every time I try to submit the form

Hey there! I've encountered an issue with my form submission. Everything works perfectly fine, except when the Title field is left blank. Here's a snippet of my HTML code: Title: <input type="text" name="title"><br /> Description:&l ...

Learn the technique of coding HTML within inline JavaScript, along with implementing CSS inline styling

I'm looking for a way to incorporate HTML within inline JavaScript, along with CSS inline styles. Can someone provide guidance on how to achieve this? For example, something like the following code snippet: <p><span style="color: #00ff00;"&g ...

Python form submission error code 405 encountered

I recently developed a simple WSGI Server using Google app engine. Here's an example of the code: import webapp2 class MainHandler(webapp2.RequestHandler): def get(self): self.response.write(''' ...

Ways to prevent decreasing the value below zero in ReactJS?

I have created two buttons, one for increasing and another for decreasing a counter value. However, when I click on the minus button, it should not display negative values. But in my case, when I click on the minus button (initially at zero), it shows -1, ...

Having trouble executing the npm start command for ReactJS

Below is the code snippet from my file named server.js if(process.env.NODE_ENV !== 'production') { require('dotenv').parse() } const express = require('express') const app = express() const expressLayouts = require(' ...

Can a React.JS application be utilized as a Micro Frontend within a container application developed using NextJS?

Currently, I am working on a NextJS webpage and hoping to incorporate a vanilla React.JS application from a separate repository into this website using Micro Frontend architecture. Is this feasible? Where should I begin in the process? I welcome all sugge ...

How Can I Transfer Queries from the Front End to the Backend Using the Fetch API?

Looking to transfer a search query from my React front end over to my Express back end in order for the Twitter API route to retrieve the correct data. The snippet below shows where I'm accessing the Twitter API. Initially, I used req.query to view JS ...

What is the method to conceal an element after detecting and locating a specific class using jQuery?

Can someone please assist me today with the following task: Step 1: <div id="htmlData"> <div class="col-md-12"> <div class="pull-left"> <h3>Report: <strong>Travel </strong></h3> ...

Guide on submitting a form in ReactJS with Material UI Dialog

I utilized the Material UI Dialog to create a form list. In the official example: <Dialog title="Dialog With Custom Width" actions={actions} modal={true} open={this.state.open} > This dialog ...

When you choose the File->Print option, the PDF contents are seamlessly printed within the document

My web page has an embedded PDF file within the content. <h3>Foo</h3> <object id="foo" data="bigboundingbox.pdf" type="application/pdf" classid="clsid:CA8A9780-280D-11CF-A24D-444553540000"> </object> When viewed in Interne ...

Creating a Slack-inspired interface with a Bootstrap 4 fixed bottom message box nested within a column

I'm attempting to create an interface similar to Slack, featuring a message box fixed at the bottom using Bootstrap 4. However, when I use the fixed-bottom class (where my custom message-box col is located), it spans the entire width of the window, wh ...

What is the best way to define the width of text inside a div block?

I'm having trouble adjusting the width of the text in my code to only fill 80% of the body element. I've tried using both the width property and padding, but neither seems to be working for me at the moment. Here's the HTML: <body&g ...

Showcasing tooltip when hovering over Font Awesome icon

My datatables grid includes some font awesome icons to represent actions like edit, delete, etc. Here's a visual representation of how they appear: https://i.sstatic.net/W0VQi.png Take a look at the accompanying HTML code: <td> <a a ...

Is it better to use enum rather than ul for inline lists within paragraphs in HTML5?

Reflecting on the passage below: So in the initial group, we merge these 3 codes: - AA - BB - CC with the following codes: - Aa - Ab - Ac to achieve the desired outcome. Is this paragraph semantically incorrect? If not, how should it be written in H ...

Enhancing Application Views in ExtJS Classic 7.3.0 using .scss Style Sheets

Referencing the guidelines provided in this resource for theming: In order to create CSS rules specific to an application view, you need to generate an .scss file within the same directory and with a matching base name as the view. For instance, if you w ...