What is the reason behind my button appearing beneath my links in React?

Here is an image showcasing the current header render. The header consists of a HeaderMenu and 3 Links. While the links are functioning properly, the HeaderMenu is causing the links to be positioned below it. The HeaderMenu includes a div that wraps a Button and Popper, creating a dropdown menu.

I'm uncertain if this design structure is ideal, but for the styling aspect, I use a styles.js file from which I extract styles. These styles are then passed down as props to the smaller components for rendering. Hence, the components here have a 'classes' prop coming from useStyles in index.js.

Header.js

import { AppBar, Button, Link, Toolbar, Typography } from '@material-ui/core'
import HeaderMenu from './HeaderMenu.js'

const Header = (props) => {
  const { classes } = props

  return (
        <AppBar position="static" color="default" elevation={0} className={classes.appBar}>
        <Toolbar className={classes.toolbar}>
          <Typography variant="h6" color="inherit" noWrap className={classes.toolbarTitle}>
            Company name
          </Typography>
          <nav>
            <HeaderMenu classes={classes}/>
            <Link variant="button" color="textPrimary" href="#" className={classes.link}>
              Here
            </Link>
            <Link variant="button" color="textPrimary" href="#" className={classes.link}>
              Enterprise
            </Link>
            <Link variant="button" color="textPrimary" href="#" className={classes.link}>
              Support
            </Link>
          </nav>
          <Button href="#" color="primary" variant="outlined" className={classes.link}>
            Login
          </Button>
        </Toolbar>
      </AppBar>
  )
}

export default Header

HeaderMenu.js

import React from 'react'
import { Button, ClickAwayListener, Grow, Paper, Popper, MenuItem, MenuList } from '@material-ui/core'

const HeaderMenu = (props) => {
  const { classes } = props
  const [open, setOpen] = React.useState(false)
  const anchorRef = React.useRef(null)

  const handleToggle = () => {
    setOpen((prevOpen) => !prevOpen)
  }

  const handleClose = (event) => {
    if (anchorRef.current && anchorRef.current.contains(event.target)) {
      return
    }

    setOpen(false)
  }

  function handleListKeyDown (event) {
    if (event.key === 'Tab') {
      event.preventDefault()
      setOpen(false)
    }
  }

  // return focus to the button when we transitioned from !open -> open
  const prevOpen = React.useRef(open)
  React.useEffect(() => {
    if (prevOpen.current === true && open === false) {
      anchorRef.current.focus()
    }

    prevOpen.current = open
  }, [open])

  return (
    <div className={classes.link}>
        <Button
          ref={anchorRef}
          aria-controls={open ? 'menu-list-grow' : undefined}
          aria-haspopup="true"
          onClick={handleToggle}
        >
          Details
        </Button>
        <Popper open={open} anchorEl={anchorRef.current} role={undefined} transition disablePortal>
          {({ TransitionProps, placement }) => (
            <Grow
              {...TransitionProps}
              style={{ transformOrigin: placement === 'bottom' ? 'center top' : 'center bottom' }}
            >
              <Paper>
                <ClickAwayListener onClickAway={handleClose}>
                  <MenuList autoFocusItem={open} id="menu-list-grow" onKeyDown={handleListKeyDown}>
                    <MenuItem onClick={handleClose}>Profile</MenuItem>
                    <MenuItem onClick={handleClose}>My account</MenuItem>
                    <MenuItem onClick={handleClose}>Logout</MenuItem>
                  </MenuList>
                </ClickAwayListener>
              </Paper>
            </Grow>
          )}
        </Popper>
    </div>
  )
}

export default HeaderMenu

Answer №1

To ensure all your links are neatly organized, enclose them within a container and insert it into your

<navigation></navigation>

display: flex;
justify-content: space-evenly;
align-items: center;

By doing this, you can maintain everything on one line.

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

Unable to stop interval in Angular 5 application

My setInterval() function seems to be working fine as the timer starts, but I am encountering an issue with clearInterval(). It does not stop the timer when the counter value reaches 100 and continues running continuously. Any help or suggestions would be ...

What is the best location for the next font in the nx workspace?

Currently, I am working in a NX workspace with Next.js and several libraries. For my component library, I am using MUI, and I have also incorporated @next/font to load a Google font. In order to maintain consistency across my application, I created a libr ...

The ZK Component fails to display within the HTML tag

In my dilemma, I am attempting to showcase a hyperlink component under an HTML tag along with some instructions for click functionality: <zk> <html> <a label="show me" onClick="@command('showMe')" /> </html> </zk ...

Errors arise when module level directives are bundled together, resulting in the 'use client' directive being disregarded and ultimately leading to a JavaScript heap memory overflow

Encountered a pipeline error in my AWS setup that said: "Module level directives cause errors when bundled, 'use client' was ignored causing JavaScript heap out of memory." Seeking a solution to this issue as I am utilizing Vite.js in my React.j ...

What is the process for implementing a decorator pattern using typescript?

I'm on a quest to dynamically create instances of various classes without the need to explicitly define each one. My ultimate goal is to implement the decorator pattern, but I've hit a roadblock in TypeScript due to compilation limitations. Desp ...

I am encountering an issue where I am unable to send a HashMap String to a PHP server, and I am not receiving a JSONArray in the

How can I send a hashmap string to a PHP server without receiving back a JsonArray using Volley in Android? CM =$_POST['code_send']; $db =Db::getInstance(); $records = $db->query ("SELECT * FROM p_users WHERE c_meli='$CM'"); $js ...

How to ensure the table fits perfectly on the screen using JQueryMobile and Cordova?

I've been working on a JavaScript function that creates a dynamic page and displays data fetched from a database. However, I've encountered an issue where the displayed data overflows past the width of the mobile screen. Is there a way to ensure ...

Tips for extracting links from a webpage using CSS selectors and Selenium

Is there a way to extract the HTML links per block on a page that renders in JavaScript? Would using CSS or Selenium be more effective than BeautifulSoup? If so, how would I go about utilizing either of those methods to achieve the extraction of the HTML ...

There was a failure in executing cb() function, which was not called. This issue points to a problem within npm. To address this error, please make a report at

npm ERR! cb() function was never called! npm ERR! This issue originates from npm itself. To address, please file a report at: npm ERR! <https://github.com/npm/cli/issues> npm ERR! For a detailed log of this process, refer to ...

PHP 5's HTML Form Library

Currently in search of an alternative to QuickForm. I have encountered performance problems with QF, specifically when dealing with a large number of options in combobox. I prefer something that is more object-oriented like Zend_Form, but without the exc ...

How to set a background image using JQuery Mobile

Struggling to apply a background image on my webpage due to JQuery Mobile CSS taking precedence over my own styling. Despite attempting the following solution, it remains unsuccessful. body { height: 100%; background-image: url('ProjectImages/log ...

Utilize jQuery and AJAX to refresh functions after each AJAX call for newly added items exclusively

I have encountered an issue with my jQuery plugins on my website. Everything functions smoothly until I load new elements via AJAX call. Re-initializing all the plugins then causes chaos because some are initialized multiple times. Is there a way to only i ...

How can I ensure that I only include a field in a JavaScript object if the value is not null?

In my current setup, I am utilizing mongoose to write data to a MongoDB collection while ensuring there are no null fields. Default values have been set in the document for this purpose. During an update function call, certain fields may be null but I do n ...

Establishing the REM value for all CSS properties

My goal is to implement the use of rem units throughout my website. However, relying on the standard rem-to-px conversion rate doesn't feel very intuitive: 10px = 0.625rem 12px = 0.75rem 14px = 0.875rem 16px = 1rem (base) 18px = 1.125rem 20px = 1.25r ...

Difficulty encountered while using Playwright with Material-UI (MUI) and anticipating the loading of MUI Grid data

I am currently running three tests. The first test involves logging in, and the second test requires clicking on the accounts tab, both of which are working as expected. However, I am facing an issue with my third test, which focuses on Account Details C ...

Convert numerical values to currency format

Here is a number 5850 that I would like to format as currency. Format Example 1: 5850 => $58.50 Format Example 2: 9280 => $92.80 I am utilizing the function below: Number.prototype.formatMoney = function(decPlaces, thouSeparator, decSeparator) { ...

Is there a feature in impress.js that allows for navigating to the following slide easily?

Impress.js is an innovative web presentation tool created with Javascript. I am interested in setting up custom events to navigate through the slides. This could involve adding buttons for "Next" and "Previous", for example. The impress.js file itself fun ...

Exploring Node.js and JSON: Retrieving specific object attributes

Utilizing ExpressJS, NodeJS, and Bookshelf.js In an attempt to display a user's list of friends, encountering the error "Unhandled rejection TypeError: Cannot read property 'friends' of undefined" when trying to access a property of the obj ...

What is the best method for transforming a base64 encoded string into a base64 formatted PDF string?

Could someone please help me with a problem I'm facing? I am utilizing an AngularJS .pdf viewer that displays documents in a modal using base64. Everything works smoothly when the base64 is generated from a .pdf file. The backend (Java) generates th ...

Using Rails to assign a page-specific CSS class within a shared layout

Is there a way to apply unique CSS classes to specific tags within a common layout? In my application.html.erb layout file, the application.css.scss is loaded using <%= stylesheet_link_tag "application". . . %>, which then includes all CSS files in ...