Is there a way to implement hover behavior for a Material-UI Button within a ButtonGroup component?

When using MUI v5, I am encountering an issue where the first button in the code provided is only half working. The button is initially colored red (both the border and text), however, upon hovering over it, the color of the border changes to blue. This is because the style is being inherited from the default blue of the ButtonGroup.

I am seeking a solution to force the first button to maintain its red border even on hover, preferably in the 'mui 5' way using sx or emotion properties.

Current behavior: the border and text of the first button are red, but the border changes to blue on hover.

Desired behavior: the border and text of the first button should remain red at all times.

Any assistance on this matter would be greatly appreciated :)

<ButtonGroup variant="outlined">
  <Button color="error">
    Again
  </Button>
  <Button>
    Good
  </Button>
</ButtonGroup>

Answer №1

To customize the styles of the first button in a button group, you can target the hover class of the button group and apply your desired styling. In MUI, the selector

MuiButtonGroup-grouped:not(:last-of-type)
is used to style the first button. You can use the pseudo-class hover of this selector to customize the styles from the surrounding div. I have modified one of the button group examples from MUI's documentation site and added CSS using the sx prop in the code sandbox below.

<Box
  sx={{
    display: "flex",
    flexDirection: "column",
    alignItems: "center",
    "& > *": {
      m: 1
    },
    ".MuiButtonGroup-grouped:not(:last-of-type):hover": { // class selector 
      borderColor: "red"
    }
  }}
>
  <ButtonGroup size="small" aria-label="small button group">
    <Button key="one" color="error">
      One
    </Button>
    ,<Button key="two">Two</Button>
  </ButtonGroup>
</Box>

Answer №2

After receiving assistance from Junaid, I decided to go with the following solution:

import {
  ButtonGroup,
  buttonGroupClasses,
  Button,
} from '@mui/material';

<ButtonGroup
  sx={{
    [`.${buttonGroupClasses.grouped}:first-child:hover`]: {
      borderColor: (theme) => theme.palette.error.dark,
    },
  }}
  variant="outlined"
>
  <Button
    color="error"
    sx={{
      width: '50%',
    }}
  >
    Again
  </Button>
  <Button sx={{ width: '50%' }}>Good</Button>
</ButtonGroup>

Some points to note:

  1. buttonGroupClasses.grouped is simply a constant exported by MuiButtonGroup-grouped from Material-UI.
  2. I had to use the computed property name, which is explained here, as a template literal string is an expression and not a regular string.

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

Is there a way to ensure that the 'pointermove' event continues to trigger even after the dialog element has been closed?

I am working on a project that involves allowing users to drag elements from a modal dialog and drop them onto the page. I have implemented a feature where dialog.close() is called once the user starts dragging. This functionality works perfectly on deskto ...

Creating visually appealing tables in React.js

Having trouble with table rendering in React. The buttons in the table cell are not styled properly and do not center within their div. Additionally, the table border is cut off where there are buttons or empty headers. Need help figuring out what's g ...

Trouble with Applying Tailwind CSS Styles in React Application Following Scraping of Next.js Page

In my Next.js application (version 13), I have various components styled with Tailwind CSS. These components are pulled from a React CMS system using Node.js and sanitized with the cheerio library. After scraping, the resulting HTML content is sent to the ...

Attention: Important update required for immer package version equals to or less than 9.0.5

In my React project, I have encountered a critical vulnerability while running an npm audit. The vulnerability is related to immer version <=9.0.5, which has been flagged for Prototype Pollution. The fix is available by running `npm audit fix --force`, ...

When attempting to add a variable using the next() function, I encountered an error with the BehaviorSubject. The error message displayed was "this.count.next is not a function"

In my Angular service, there is a variable called count that I need to monitor for updates. Whenever this count variable is updated, I want to assign its new value to another variable in a separate component. import {BehaviorSubject} from "rxjs/BehaviorSu ...

Mastering the alignment of tab content on Bootstrap 5 to ensure it always displays on the right side

With Bootstrap 5, I've managed to implement tab content that remains visible regardless of the active tab: <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="23414c4c5750575142536 ...

What is the rationale behind using :: before display: inline-block in Angular Material MDC's mat-mdc-form-field-error-wrapper, causing substantial padding?

I recently made the switch from Angular Material to Angular Material MDC in preparation for upgrading to Angular 17 from version 15. However, I've noticed that some styles are now broken. One issue I'm facing is a significant padding between the ...

Checking if a start date comes after an end date using Yup - how is it done?

How can I use Yup to validate if the start date overlaps with the end date in a form that creates an event using Formik library? I have two date pickers for choosing the dates and times. I want to display an error message if they overlap. Thanks for the ...

Encountering a CORS issue when trying to deploy a MERN Stack application on VERCEL for both the client and server components

I successfully deployed both the client and server code on Vercel. The registration process involves sending email IDs and other information from the client side to the server side, where they are stored in an online MongoDB Atlas database. However, I enco ...

Using TypeScript's type casting functionality, you can easily map an enum list from C#

This is a C# enum list class that I have created: namespace MyProject.MyName { public enum MyNameList { [Description("NameOne")] NameOne, [Description("NameTwo")] NameTwo, [Description("NameThree")] NameThree ...

Is it possible to modify the font color of a specific MenuItem in material-ui?

I've scoured every corner of the internet, but I'm still stumped by this question: How can I tweak the text color (not the background) for a selected or hovered MenuItem? I know the solution lies within useStyles, but my attempts thus far have be ...

Tips for mocking a module with a slash character in its name?

When it comes to mocking a standard npm project, the process is simple. Just create a __mocks__ folder next to the node_modules folder, then name the file after the package and insert the mock contents. For example: /__mocks__/axios.ts However, I encount ...

Ways to conceal #div element from displaying in the href attribute within the anchor tag

My anchor tag has an href attribute that looks like this: <a onclick='loadReview(\"" + strexternalURL + "\");' href='#productName1'. When clicking on it, the URL appears as http://localhost:54986/Dealerlist.aspx#productName ...

Can you explain the function of mdLiveAnnouncer in Angular Material and how it operates?

Could someone provide an explanation of $mdLiveAnnouncer using this code snippet? module.controller('AppCtrl', function($mdLiveAnnouncer) { // Making a basic announcement (Polite Mode) $mdLiveAnnouncer.announce('Hey Google'); // ...

Is it possible to convert JSON to enum using TypeScript?

I have a JSON string that looks like the following. { "type": "A", "desc": "AAA" } or { "type": "B", "desc" "BBB" } etc. How can I utilize an enum in Ty ...

Strange spacing below body element discovered while browsing website in Firefox 7

Currently, I am facing an issue on my website in Firefox 7. A margin is causing the gradient in #wrapper to shift upwards from the bottom, disrupting the layout. Despite resetting the margin to 0 on body and html, I am unable to pinpoint the root of the pr ...

using mixins with styled-components

I have encountered a challenge while attempting to pass a mixin from Material UI to a styled-component. The problem lies in finding a way to transfer the mixin value to the styled-component without having to assign it to a css property. Unfortunately, dire ...

Error: The module 'react' was not found in Material-ui List

Hey there, I recently completed the React official tutorial and got my tic-tac-toe game up and running smoothly. Excited to enhance it with some material-ui components, I went ahead and installed them using: npm install --save @material-ui/core npm instal ...

What is the best way to center align an element vertically in my specific situation

Struggling to vertically align elements within a div? Here's a snippet of code that might help: Here's a sample of what you might have: html <div class="test"> <a href="#"><img src="test.png"/></a> <a href="# ...

What is the best way to assign a background image to a div in React Js?

Is there a way to set an image as the background of a div in React without using a const? I need the image to serve as a background image so that I can overlay text on top of it. I am looking for a solution that doesn't involve hardcoding the backgr ...