'How to set border color using MUI styled components?

I am trying to add a border color to a styled component using MUI:

const Style = styled('div')(({ theme }) => ({
    display: 'flex',
    flexDirection: 'column',
    borderColor: theme.palette.success.main,
    border: 10, 
    borderTop: 10,
    width: INFO_WIDTH
}));

However, I don't see any change in the effect: Screenshot of browser

I'm trying to follow the guidelines specified by MUI but it's not working. Does anyone know a workaround?



Solution 1:[1]

The guidelines you linked to are for the sx prop (or lower-level usage of @mui/system) -- not the styled API. One key difference between the two is that for the sx prop, a numeric border value is treated as a shorthand for ${value}px solid. The styled API does not automatically add solid, so border: 10 just becomes border: 10px which is not sufficient for causing a border to be displayed.

A separate issue with your example is that you specify borderColor before border. Since border is a shorthand for border-width, border-style, and border-color, even when you don't specify a color with the border value, a previously specified border-color will be overridden with the default.

Below is an example showing the correct syntax for specifying the border for both sx and styled:

import * as React from "react";
import Box from "@mui/material/Box";
import { styled } from "@mui/material/styles";

const StyledDiv = styled("div")(({ theme }) => ({
  border: "10px solid",
  borderColor: theme.palette.success.main,
  width: "5rem",
  height: "5rem",
  margin: theme.spacing(1)
}));
export default function BorderSubtractive() {
  return (
    <Box sx={{ display: "flex", justifyContent: "center" }}>
      <Box
        sx={{
          border: 10,
          borderColor: "success.main",
          width: "5rem",
          height: "5rem",
          m: 1
        }}
      />
      <StyledDiv />
    </Box>
  );
}

Edit Border MUI Demo

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ryan Cogswell