Activate a Dropdown Menu by Clicking in a React Application

I have a collapsible feature where you can click to expand or collapse a dropdown. Currently, the dropdown can only be clicked on where the radio button is located. I want the entire area to be clickable so that users can choose the dropdown by clicking anywhere within that area. How can I achieve this?

https://i.stack.imgur.com/5wqDI.png

View Codesandbox example here: CLICK HERE

<Collapse in={expanded} timeout="auto" unmountOnExit>
  <Card className="mb-2">
    <CardContent className="p-0">
      <FormControl className="w-100" component="fieldset">
        <RadioGroup value={activeOption} onChange={onSubOptionClicked}>
          {subOptions.map((subOption) => (
            <ListSubOptionItem
              {...subOption}
              activeOption={activeOption}
              key={subOption.label}
            />
          ))}
        </RadioGroup>
      </FormControl>
    </CardContent>
  </Card>
</Collapse>

Answer №1

Make updates to the ListSubOptionItem component so that all visual elements act as clickable controls.

import {
  ...,
  FormControlLabel as BaseFormControlLabel,
  ...,
  styled,
} from "@mui/material";
const StyledListSubOptionLabel = styled(ListItemText)({
  marginTop: "-4px !important"
});

...

const FormControlLabel = styled(BaseFormControlLabel)({
  alignItems: "baseline", 
  ".MuiFormControlLabel-label": {
    flexGrow: 1, 
  },
});
const ListSubOptionItem = ({
  imgUrl,
  label,
  subLabel,
  maxWidth,
  disabled = false,
  value = null,
  activeOption = null
}) => {
  return (
    <FormControlLabel
      disabled={disabled ?? false}
      className={classNames("m-0 sub-option-item", {
        active: activeOption === value
      })}
      control={<StyledRadio />}
      label={
        <StyledListSubOptionItemWrapper
          className={classNames("d-flex justify-content-between py-3 pr-3", {
            "align-items-start": !!subLabel,
            "align-items-center": !subLabel
          })}
        >
          <Stack>
            {label}
            {subLabel && (
              <StyledListSubOptionLabel
                classes={{ secondary: "text-gray" }}
                secondary={subLabel}
              />
            )}
          </Stack>
          {imgUrl && (
            <img
              src={imgUrl}
              alt={imgUrl}
              {...(subLabel && { className: "mt-1" })}
              style={{
                opacity: disabled ? 0.2 : 1,
                maxWidth: maxWidth ?? "80px",
                width: "100%"
              }}
            />
          )}
        </StyledListSubOptionItemWrapper>
      }
      value={value}
    />
  );
};

https://codesandbox.io/s/intelligent-resonance-9nkpxk?expanddevtools=1&fontsize=14&hidenavigation=1&module=%2FListOptionItem.tsx&theme=dark

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

The dropdown on my website is malfunctioning

There seems to be an issue with my dropdown button. Previously, it only appeared when clicking on a specific part of the button. I attempted to resolve this problem but unfortunately, the dropdown no longer works at all and I am unable to revert my changes ...

What is the method by which Morgan middleware consistently displays the output on the console following the execution of all other middleware

Utilizing the express library along with the logging library known as morgan Provided below is a snippet of working code that can be used to reproduce this in nodejs: const express = require('express') const morgan = require('morgan') ...

Is it possible to optimize SEO for Mern Stack and reactjs applications?

As a newcomer to the world of development, I recently undertook the exciting challenge of creating a MERN Stack Application. This involved using reactjs for the frontend, Nodejs with express for the Backend, and MongoDB as the Database. However, upon reali ...

Making the text gradually disappear at the bottom of a section using a see-through overlay, while ensuring the height remains within the boundaries of the section even

Trying to achieve a sleek fade-out effect at the end of a text section for a 'read more' indicator. I've been studying various tutorials, including this, and my current code is as follows: html <section> <p>Lorem ipsum dol ...

Looking for assistance in minimizing the gap between the banner and content on my Weebly website

Currently, I am utilizing Weebly templates and working with the CSS files for my website located at www.zxentest.weebly.com. I am seeking assistance in reducing the space between the yellow banner and the faint line on either side, as well as decreasing t ...

Tips for resolving the NextJS port already in use issue

My ReactApp is up and running smoothly on port 3000. However, when I decided to launch a new NextJS App for testing purposes, an error popped up: Error: listen EADDRINUSE: address already in use 0.0.0.0:3000 This situation doesn't add up. In a nor ...

How to display an external link page in a popup using React

I'm having trouble displaying the Google page in my popup. When I try to load it, I get a message in the iframe saying 'www.google.com refused to connect' App.js import React from 'react'; import Popup from './components/Pop ...

What causes TypeScript to malfunction when using spread in components?

What is the reason for typescript breaking when props are sent to a component using a spread statement? Here's an example code snippet: type SomeComponentProps = Readonly<{ someTitle: string }> const SomeComponent = ({ someTitle }: SomeCompo ...

What causes addEventListener to not return a value?

In this snippet of code: let rockClick = rockBtn.addEventListener('click', playRound.bind("rock", computerPlay(), false)); After using console.log(), the output is undefined. The purpose of rockBtn:const rockBtn = document.querySelecto ...

Customizing color schemes of bootstrap buttons and dropdown-toggle elements

My button group looks like this: HTML <div class="btn-group"> <button type="button" class="btn btn-default btn-xs red-outline-button"> Sync </button> <button type="button" class="btn btn-default btn-xs gold-outline-button" da ...

Exploring the world of cookie security with SameSite and Secure features in ExpressJS

Despite having the specified settings on my express application, a warning keeps appearing in the console. Has anyone encountered this error before? I found some information related to it here: https://github.com/expressjs/express/issues/3095 The version ...

Can the content inside HTML tags be susceptible to XSS attacks?

While working with Codeigniter, I have noticed that the xss_clean() function is replacing tab characters with a single space character. This behavior ends up causing issues when the content is later displayed within <pre><code></code>< ...

Tips for changing the color of shapes when hovering over an image state

I have arranged three images in a column and applied column-count: 3; along with setting border-width for those images. Now I am curious about how to create the hover state for these images. Here is the HTML code snippet: <div class="wrap"> < ...

Having trouble retrieving the $scope value in HTML, even though it was assigned within the success function of $http.post

Having trouble accessing the values of $scope properties after a successful $http post in index.html file. Here is the code snippet for reference, any help in resolving this issue would be greatly appreciated as I am new to AngularJs var app = angular.m ...

Unable to access res.name due to subscription in Angular

Right now, I am following a tutorial on YouTube that covers authentication with Angular. However, I have hit a roadblock: The code provided in the tutorial is not working for me because of the use of subscribe(), which is resulting in the following messag ...

What could be causing the CSS to not display properly on specific routes?

I'm facing an issue where CSS seems to be working fine for certain routes with node.js & express, but not for others. It's puzzling because the HTML file links to the same CSS file in both cases. For instance, CSS works perfectly for the route " ...

Can you explain the meaning of the color enums "inherit" and "default" in Material-UI?

The color of a component in Material UI can be set as either 'default', 'inherit', 'primary', or 'secondary'. But what do "default" and "inherit" actually mean in this context? It seems that some components have a d ...

Can you suggest the best HTML5 structure for a multi-chapter novel?

In the process of creating a small HTML5 book with chapters and sections, I encountered a dilemma when it comes to structuring my documents like this: chapter1.html - introduction to chapter 1 chapter1section1.html - section 1.1 chapter1section2.ht ...

implement a new directive in AngularJS that references another directive in HTML

Check out the Fiddle here Upon button click, a modal window appears. Inside this modal, there is a <template-placeholder></template-placeholder>. When the button is clicked, an if-check is performed to ensure it's the correct button. If ...

How to Use Absolute Positioning in Bootstrap 3.0 to Position Child Divs

I have a div block that needs to always be displayed at the bottom of the section, regardless of whether the section above is empty. The inner div should stay at the bottom of the section, as shown in the attached image. This is my current code: <div ...