Step-by-step guide on programmatically closing the Material-UI DropDownMenu

http://www.material-ui.com/#/components/dropdown-menu

Having encountered a styling issue, I was compelled to rearrange the order of components within my material-ui DropdownMenu.

Nevertheless, some buttons (renderNavLink) are now failing to close the Dropdown once clicked.


Here's how I'm rendering:

render() {
  return (
    <ToolbarGroup>
      <DropdownMenu value={defaultSelection} className="quick-dropdown">
        {this.renderMenuItems()}
      </DropdownMenu>
    </ToolbarGroup>
  );
}

The renderMenuItems method

The issue lies within the renderNavLink function

renderMenuItems() {
  return menuItems.map((item, i) => {
    if (item.to) return renderNavLink(i, item, closeMenu);
    return renderClickable(i, item, this.props);
  });
}

The renderNavLink function

I've included the closeMenu function, but currently it only logs to console

const renderNavLink = (i, { to, primaryText: value }, closeMenu) => (
  <NavLink
    key={i}
    to={to}
    style={navLink.default}
    onClick={closeMenu}
  >
    <MenuItem key={i} value={value}>
      {value}
    </MenuItem>
  </NavLink>
);

closeMenu

const closeMenu = () => {
  console.log('closeMenu...');
};

Complete Component Code

/* eslint-disable react/no-array-index-key */
import React from 'react';
import { NavLink } from 'react-router-dom';
import { connect } from 'react-redux';

// Material UI Components
import { ToolbarGroup } from 'material-ui/Toolbar';
import DropdownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';

// Actions
import { closeModal, setModal } from 'actions/Modals';

// Styles
import { navLink } from 'components/Styles/material';

// Copy
import { MODAL_CREATEDRAFT_NAME } from 'copy';

// Utils
import { cleanMapStateToProps } from 'utils';

const menuItems = [{
  primaryText: 'Quick Menu',
  className: 'quickmenu-navlink'
}, {
  primaryText: 'Create Draft',
  className: 'quickmenu-navlink',
  modal: MODAL_CREATEDRAFT_NAME
}, {
  primaryText: 'My Drafts',
  to: '/drafts/mine'
}, {
  primaryText: 'Active Drafts',
  to: '/drafts/active'
}, {
  primaryText: 'Archived Drafts',
  to: '/drafts/archived'
}, {
  primaryText: 'Environment Status',
  to: '/drafts/environments'
}];

const defaultSelection = menuItems[0].primaryText;

const renderNavLink = (i, { to, primaryText: value }, closeMenu) => (
  <NavLink
    key={i}
    to={to}
    style={navLink.default}
    onClick={closeMenu}
  >
    <MenuItem key={i} value={value}>
      {value}
    </MenuItem>
  </NavLink>
);

const renderClickable = (i, {
  modal, onClick, className, primaryText: value
}, {
  setModal: setModalAction
}) => (
  <MenuItem
    key={i}
    value={value}
    primaryText={value}
    style={navLink.special}
    className={className || ''}
    onClick={modal ? () => setModalAction(modal) : onClick}
  />
);

const closeMenu = () => {
  console.log('closeMenu...');
};

class QuickMenu extends React.Component {
  componentWillReceiveProps(nextProps) {
    const { currentDraft } = nextProps;

    if (currentDraft && currentDraft.id) {
      this.props.closeModal();
    }
  }

  renderMenuItems() {
    return menuItems.map((item, i) => {
      if (item.to) return renderNavLink(i, item, closeMenu);
      return renderClickable(i, item, this.props);
    });
  }

  render() {
    return (
      <ToolbarGroup>
        <DropdownMenu value={defaultSelection} className="quick-dropdown">
          {this.renderMenuItems()}
        </DropdownMenu>
      </ToolbarGroup>
    );
  }
}

export const QuickMenuJest = QuickMenu;

const mapDispatchToProps = dispatch => ({
  closeModal: (...args) => { dispatch(closeModal(...args)); },
  setModal: (...args) => { dispatch(setModal(...args)); }
});

export default connect(cleanMapStateToProps(['location', 'currentDraft']), mapDispatchToProps)(QuickMenu);

Answer №1

After troubleshooting, I discovered that my issue stemmed from a CSS problem. I was able to resolve it by implementing the following class:

render() {
    return (
      <ToolbarGroup>
        <DropdownMenu value={defaultSelection} className="custom-dropdown">
          {this.renderMenuItems()}
        </DropdownMenu>
      </ToolbarGroup>
    );
  }

.custom-dropdown {
  position: fixed !important;
  right: -20px !important;
}

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

How can progress bars be animated using CSS or JavaScript?

I am currently working on creating a progress bar animation, but I'm unsure whether to use CSS or JS. Can anyone provide insight on how this effect was achieved here? I am hoping to replicate it. Does anyone know if this is the code they used? I&apos ...

The Wordpress plugin's Ajax function is giving back a response value of zero

I'm facing an issue where I am attempting to send AJAX data to my wordpress table, but the response I receive from my PHP script is always a 0. This problem arises specifically on the admin side of things. Can anyone provide assistance? Furthermore, ...

Using TypeScript and React: Implementing interfaces based on props conditions

I am currently designing a component that must either receive a prop named text or children, but not both or neither. ✓ Allow <NotificationBar text="Demo"/> <NotificationBar>Demo</NotificationBar> ✗ Disallow <NotificationBar/&g ...

Implementing conditional reduction in JavaScript arrays

I've encountered an issue with the filter and reduce methods. I am attempting to calculate the sum of "smc" values only when "A" equals 2020 from the given array below: arr = [{A:2020, smc:1},{A:2020, smc:2}, {A:2021, smc:3}] My attempted solution so ...

The Vanilla JS script in Next.js fails to execute upon deployment

Currently developing a simple static site with Next.js. The lone vanilla JS script in use is for managing a mobile menu - enabling toggling and adding a specific class to disable scrolling on the body: if (process.browser) { document.addEventListener(&ap ...

Determining the maximum number within an array using JavaScript

Similar Question: How can I identify the largest number in a JavaScript array? I'm facing issues with this piece of code. Despite spending some time on it, I can't seem to make it work properly. The console only shows 0 when I run it. Can som ...

Enhance the MUI palette by incorporating TypeScript, allowing for seamless indexing through the palette

When utilizing the Material UI Palette with Typescript, I am encountering a significant issue due to limited documentation on MUI v5.0 in this area. Deep understanding of typescript is also required. The objective is to iterate through the palette and vir ...

Issue with the z-index of Antdesign Select component when using it with Portal

I'm currently dealing with a situation like this: <Portal> <BigComponent> <Select options={[...]} /> </BigComponent> </Portal> The dropdown select options are being generated in a neighboring div to the BigComp ...

Issue with Fullcalendar's events.php causing JSON object retrieval failure

I'm attempting to send a JSON object as a response to my fullcalendar ajax request, but instead of returning the desired result, it only returns an array. Although I am relatively new to JSON and PHP, I have conducted extensive research and have yet t ...

``req.body is not being properly populated when data is sent using form-data, causing

When I send data in my Node.js application as raw JSON/x-www-form-urlencoded from Postman, it gets passed successfully. However, when sending the data as form-data from either Postman or my Angular frontend, the req.body is coming back as undefined. I have ...

What is the best way for me to bring in this function?

Currently, I am in the process of developing a point-of-sale (POS) system that needs to communicate with the kitchen. My challenge lies in importing the reducer into my express server. Despite multiple attempts, I have been unable to import it either as a ...

Tips for verifying a login modal on an asp.net webforms using jQuery?

I am currently working on an asp.net webpage that utilizes a modal bootstrap for user login. Upon clicking the Login button, it should authenticate the user and initiate a server-side method called "ExportToZip" to download a zip file. My issue lies in ens ...

Despite setting `staleTime` to Infinity, React Query continues to trigger refetches

export function retrieveAllUsers() { return useQuery<UserResponseDto[]>({ queryKey: [QueryClientKeys.GET_ALL_USERS], queryFn: async () => { const response = await http.get< UserResponseDto[], ...

There are various IDs in the output and I only require one specific ID

I have a JSON fetcher that is functioning properly. However, whenever I request an ID, it returns all the IDs present in the JSON data. Is there a way to retrieve only the latest ID? This is my first time working with JSON so I am still learning. $(docu ...

If the MUI autocomplete is unable to retrieve the value from the multiple attribute, it will either return 0 or remain undefined

When using the MUI Autocomplete component with the 'multiple' attribute, the value prop may return 0 or undefined when selecting an option. <Autocomplete value={v.education} onChange={handleEducationChange} className={classes.textOutline ...

Storing filtered data objects for future use

Introduction to my User Administration Page Currently, I am working on the User Administration page of my project and facing a minor issue. The page includes a table that displays material-ui's Usercard for each user in the system. These cards are ge ...

Tips on adjusting font size of material ui badge text in reactjs?

I am attempting to adjust the font size of the label within a material ui badge. The current method I am using, style={{ fontSize: "15" }}, only impacts its child element, which happens to be an icon. Sample Code: <Badge badgeContent={props.c ...

Load ajax content dynamically based on the updated URL

Exploring ajax for the first time and having some issues. Currently, I am retrieving text from files based on the URL. This is how it's set up: var home_url = "blahblah/index.html#home"; var test_url = "blahblah/index.html#test"; $(document).on("c ...

Scroll up and down to witness the enchanting interplay of fading in and out

Looking to expand upon the solution given in this response. The existing code effectively fades in an element while scrolling down and fades out an image when scrolling up; however, it lacks the functionality to fade out when scrolling down. I am aiming ...

Express get requests are failing to handle query strings

Whenever I try to extract the year and month from the URL like this: http://localhost:3000/api/posts/2018/4, the code doesn't seem to work properly. Instead, it returns an error saying: Cannot GET /api/posts/2018/4 Here's the JavaScript code I&a ...