Home > Back-end >  How to style the border of the ListItemButton when selected in Material UI?
How to style the border of the ListItemButton when selected in Material UI?

Time:08-04

I have the functionality where if the ListItemButton is selected, it will highlight it with a given background color. But now I want to style the ListItemButton even more by adding an outline or border color around it when selected. I used the attribute borderColor but currently it is not working.

Button but not border or outline style when selected

Source code:

 /* eslint-disable react/react-in-jsx-scope -- Unaware of jsxImportSource */
/** @jsxImportSource @emotion/react */
import { useState } from "react";
import ListItemButton from "@mui/material/ListItemButton";
import { css } from "@emotion/react";


export default function TestSample() {
  

  const [selected2, setSelected2] = useState(false);

  return (
    <div className="App">
      <ListItemButton
        sx={{
          "&.Mui-selected": {
            backgroundColor: "#02A7DD",
            borderColor: "red",
          },
          "&.Mui-focusVisible": {
            backgroundColor: "#02A7DD",
            borderColor: "red",
          },
          ":hover": {
            backgroundColor: "#02A7DD",
            borderColor: "red",
          },
        }}
        selected={selected2}
        onClick={() => setSelected2((prev) => !prev)}
      >
       ListItemButton
      </ListItemButton>

      
    </div>
  );
}

Hoping for your responses as this would help me a lot especially since I am exploring MUI at the moment an trying to understand its use and implementation. Thank you very much!

CodePudding user response:

You're missing the borderWidth and borderStyle properties. Right now you have a red border that is invisible and 0 pixels thick.

As a shorthand you can specify just the border property instead, for example:

sx={{
    border: '1px solid red'
}}

which is the same as

sx={{
    borderStyle: 'solid',
    borderWidth: '1px',
    borderColor: 'red'
}}
  • Related