7
votes

I am using a material-ui button and trying to override the border-radius (i.e, make it 0) through styled-components. However, it's not working.

Code:

import React from "react";
import styled from "styled-components";
import { Button } from "@material-ui/core";

const StyledButton = styled(Button)`
  background-color: #d29d12;
  border-radius: 0;
`;

export default function App() {
  return <StyledButton>Hello</StyledButton>;
}
5

5 Answers

7
votes

By default, Material-UI injects it styles at the end of the <head> element. This means that its styles will come after styles generated by styled-components and thus the Material-UI styles will win over the styled-components styles when CSS specificity is the same.

You can use the StylesProvider component with the injectFirst property to move the Material-UI styles to the beginning of the <head> and then the styled-components styles will come after it and win.

import React from "react";
import styled from "styled-components";
import Button from "@material-ui/core/Button";
import { StylesProvider } from "@material-ui/core/styles";

const StyledButton = styled(Button)`
  background-color: red;
  border-radius: 0;
`;

export default function App() {
  return (
    <StylesProvider injectFirst>
      <div className="App">
        <StyledButton>Hello</StyledButton>
      </div>
    </StylesProvider>
  );
}

Edit styled-components

Related answers:

3
votes

Use styled-components higher specificity syntax: https://styled-components.com/docs/faqs#how-can-i-override-styles-with-higher-specificity

const StyledButton = styled(Button)`
  && {
    background-color: red;
    border-radius: 0;
  }
`;
1
votes

By adding className to StyledButton, it can override MUI button style,

<StyledButton className={'myclassName'}>Hello</styledButton>

const StyledButton = styled(Button)`
 &.myclassName {
    background-color: red,
    border-radius: 0
  }
`;

0
votes

const StyledButton = styled(Button)({
  '&&&': {
    backgroundColor: red,
    borderRadius: 0
  }
)}
-5
votes

You can override the default border-radius of button by applying !important to your styled component.

const StyledButton = styled(Button)`
  borderRadius: 0px !important;
`;