What is the best way to activate materialise pop-up menus in a React application?

Looking to enhance my React app by adding a NavBar with dropdown functionality. Here's the code snippet:

<ul id="dropdown1" className="dropdown-content">
          <li><NavLink to="/create">Create lessons</NavLink></li>*/}
                <li><NavLink to="/lessons">Lessons</NavLink></li>
                <li><NavLink to="/quizes">Quizes</NavLink></li>
                <li><NavLink to="/quizcreator">Create QuizGame</NavLink></li>
                <li></li>
                <li></li>
        </ul>

  <nav>
    <div className="nav-wrapper">
      <a href="#!" className="brand-logo">Logo</a>
      <ul className="right hide-on-med-and-down">
        <li><NavLink to="/home">Home</NavLink></li>
        <li><a className="dropdown-trigger" href="#!" data-target="dropdown1">Dropdown<i
            className="material-icons right">arrow_drop_down</i></a></li>
        <li><a href="/" onClick={logoutHandler}>Logout</a></li>
      </ul>
    </div>
  </nav>

https://i.stack.imgur.com/MEBM1.png

Interested in making the dropdown menu open on click or hover, as demonstrated in this materialize css example.

$(".dropdown-trigger").dropdown();

Seeking guidance on where to insert this code for my MERN stack application.

Answer №1

<!--Include Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<!-- Compressed and minimized CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

<!-- Compressed and minimized JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>


<!-- Dropdown Configuration -->
<ul id="dropdown1" class="dropdown-content">
  <li><a href="#!">one</a></li>
  <li><a href="#!">two</a></li>
  <li class="divider"></li>
  <li><a href="#!">three</a></li>
</ul>
<nav>
  <div class="nav-wrapper">
    <a href="#!" class="brand-logo">Logo</a>
    <ul class="right hide-on-med-and-down">
      <li><a href="sass.html">Sass</a></li>
      <li><a href="badges.html">Components</a></li>
      <!-- Dropdown Trigger -->
      <li><a class="dropdown-trigger" href="#!" data-target="dropdown1">Dropdown<i class="material-icons right">arrow_drop_down</i></a></li>
    </ul>
  </div>
</nav>

Answer №2

Based on the information provided in the official documentation, you can activate all your dropdowns by using the following code snippet:

document.addEventListener('DOMContentLoaded', function() {
  var elems = document.querySelectorAll('.dropdown-trigger');
  var instances = M.Dropdown.init(elems);
});

For a practical demonstration, refer to this example (preferably open it in full-page mode):

document.addEventListener('DOMContentLoaded', function() {
  var elems = document.querySelectorAll('.dropdown-trigger');
  var instances = M.Dropdown.init(elems);
});
<!--Import Google Icon Font-->
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<!-- Compiled and minified CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

<!-- Compiled and minified JavaScript -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

<!-- Dropdown Structure -->
<ul id="dropdown1" class="dropdown-content">
  <li><a href="#!">one</a></li>
  <li><a href="#!">two</a></li>
  <li class="divider"></li>
  <li><a href="#!">three</a></li>
</ul>
<nav>
  <div class="nav-wrapper">
    <a href="#!" class="brand-logo">Logo</a>
    <ul class="right hide-on-med-and-down">
      <li><a href="sass.html">Sass</a></li>
      <li><a href="badges.html">Components</a></li>
      <!-- Dropdown Trigger -->
      <li><a class="dropdown-trigger" href="#!" data-target="dropdown1">Dropdown<i class="material-icons right">arrow_drop_down</i></a></li>
    </ul>
  </div>
</nav>

Answer №3

Make sure to include an onclick event in your second list item ("li"). Pass the event object as a parameter, and then call the dropdown() function by retrieving the classname from the event object.

<li>
    <a className="dropdown-trigger" href="#!" onclick{(e) => e.target.className.dropdown();} data-target="dropdown1">
       Dropdown<i className="material-icons right">arrow_drop_down</i>
    </a>
</li>

Answer №4

Just follow these simple steps to make it work effortlessly!

Simply insert the following code snippet into your JavaScript file:
document.addEventListener('DOMContentLoaded', function() {
  var elems = document.querySelectorAll('.dropdown-trigger');
  var instances = M.Dropdown.init(elems);
});

If you're facing issues with the dropdown functionality, it's probably because you haven't initialized it properly! Consider using a different framework like MDbootstrap, which offers a React version and comprehensive documentation without any intrusive ads.

Answer №5

It seems that you are currently working with React and, based on the resource provided in your question, using

$(".dropdown-trigger").dropdown();
follows the jQuery approach. To integrate this functionality in a more suitable manner for React, you will need to discover the React way

To address this, consider installing the materialize-css package. Additionally, I recommend checking out How to use materialize-css with React? as it may offer valuable insights into achieving this integration

After installation, proceed to import and utilize the package utilizing the following steps:

import React, { useRef, useEffect } from 'react';
import M from 'materialize-css';

function DropDown() {
    const dropDownTriggerRef = useRef();
    
    useEffect(() => {
      M.Dropdown.init(dropDownTriggerRef.current);
    }, [])

    return (
           // include other necessary components and elements
           ....
           <li>
              <a className="dropdown-trigger"
                 href="#!" data-target="dropdown1"
                 ref={dropDownTriggerRef}
              >
                  Dropdown
                  <i className="material-icons right"> arrow_drop_down </i>
              </a>
           </li>
          ....
    );
}

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

Ways to retrieve information from a POST request

I am looking for assistance on extracting data from a post request and transferring it to Google Sheets while also confirming with the client. Any guidance or support would be highly appreciated. Thank you. My project involves creating a web application f ...

Can CSS be utilized to consistently display text in a uniform manner?

Currently developing a unique Qur'an app for Muslims, standing out from the already existing ones in the market. There are two common types of Qur'an apps available: one that replicates the exact look of a physical copy, page by page, using imag ...

Responsive design is key in ensuring that Bootstrap columns adjust accordingly

I am attempting to create a responsive block in the center of my webpage with the help of Bootstrap. However, I am having trouble getting the columns to respond correctly to my bootstrap setup. Can anyone point out what I might be doing wrong? <lin ...

Icon not appearing within the input group

Is there a way to design an input group that includes both a text field and an icon placed at the beginning of the text field? The code below demonstrates my attempted implementation, however, it appears that only the text field is visible without the acco ...

Nextjs attempting to access local storage without proper initialization

I'm currently working on a feature where I have a sidebar with two buttons, contact and profile. When a user clicks on either of them, the URL updates to: /?section=clickedItem, allowing the user to save the state and return to that specific page upon ...

Issue with React Native Hook where converting a function into a class variable results in 'undefined'

We are currently in the process of converting a react native function into a class so that we can implement state management compatible with Firebase's real-time database. It recently came to our attention that Hooks cannot be used within a class, so ...

To properly handle this file type in React, ensure you have the correct babel loader installed

An error is triggered when trying to compile with webpack. The message indicates that an appropriate loader may be needed to handle this file type. The libraries I am using are: Below are my project files: package.json { "name": "react", "version": ...

Detecting the scroll events of elements with the overflow:hidden property

Looking to synchronize scrolling between two different panels or divs? In one element, there's an overflow: auto while the other has overflow: hidden (trying to mimic a grid with frozen columns). I've managed to sync the scroll when it occurs w ...

How come the new background isn't showing up when using styled-components?

My goal is to fetch an image URL from an API and utilize it as a background in my application, requiring the use of styled-components. Below is the code for my app: const API_KEY = `some key`; class App extends React.Component{ constructor() { ...

Dynamically include a new prop to the final element within an array of React components

I have been searching everywhere for a solution to this problem, but I can't seem to find one as I am unable to edit the props object. Here's what we are currently doing. We have a menu with subsections and we achieve this by: const firstSectio ...

Observer function simulated by SinonStub

I am currently testing express middleware using sinon.js My goal is to verify that it sends a specific JSON response and prevents the request from moving on to the next middleware or request handler. const middleware = (req: Request, res: Response, nex ...

ACE.js enhances website security through Content Security Policy

I've been working on setting up a helmet-csp with ace running smoothly. Here's how my helmet-setup looks: var csp = require("helmet-csp"); app.use(csp({ directives: { defaultSrc: ["'self'", "https://localhost:8000"], ...

Overflow container list items in Bootstrap

How can I prevent the text in each item of this dropdown list from wrapping and display them in a single line? .autocomplete-items { /* position: absolute; */ /* border: 1px solid #ccc; */ /* border-top: none; */ /* border-radius: 0 0 ...

The table borders in IE 11 do not display properly when using Html5 and CSS

In a previous version, the table had visible borders. However, when I added the property text-align:center; to my container, the table did not align to the center. I then tried adding display:inline-block; to the table, which successfully centered it. It l ...

Querying mongoose for date and time ranges

Hello, I am seeking assistance with resolving a particular issue. My dilemma involves querying data based on a specific date and time range in Mongoose. The timeframe in question is between 2016-09-25T00:00:10.000+07:00 and 2016-09-25T01:00:10.000+07:00. ...

Exploring the implementation of TypeScript Generics in react-hook-form interfaces

This is the code I have: export interface PatientFormInputs { patientId: string; firstName: string; lastName: string; email: string; day: string; month: string; year: string; } In a React component: const { control, register, h ...

The API endpoint returns a 404 not found error on NextJS 14 in the production environment, while it functions correctly on the local

I am in the process of creating a small website using NEXT JS 14. On my website, there is a contact us page that I have been working on. In the GetInTouch.tsx file, I have the following code: <Formik initialValues={{ ...

Revamp the appearance of angular material inputs

I have been working on customizing the style of an Angular Material input. So far, I successfully altered the background-color with the following code: md-input-container { padding-bottom: 5px; background-color: #222; } I also changed the placeh ...

Issue with jQuery centering in IE browsers with jquery-ui-1.10.3.custom.js and jquery-ui-1.9.2.custom.js not working as expected

Are there any other alternatives you can recommend? Here is the dialog structure: <div id="dialogbox" title="message box"> <p>example content</P> </div> ...

Troubleshooting problem with JQuery window printing capability

After creating a paper with dimensions of 21.0 cm width and 29.7cm height, I encountered an issue where the printer output three papers instead of just two. I am not sure where I went wrong in my setup. You can find the source code here. window.print(); ...