I have been in this error for quite a while now in my React application but can’t seem to find a solution nor a logical explanation. I’m using Material-UI v6 and styled-components.
I have this styled component (AppBar.styled.js):
import styled from "styled-components";
import { AppBar } from "@mui/material";
const StyledAppBar = styled(AppBar)`
margin: 20px; //${(props) => props.theme.palette.tertiary.main};
background-color: darkorange;
`;
export default StyledAppBar;
And curiously, the margin property is correctly applied to the appbar but the background-color is not:
I can’t seem to figure out why nor a solution. Can some one care to exaplain what is happening and how can I solve this? I already tried to add the StyledEngineProvider
but still no changes. This is how the App.js looks like:
import { Fragment } from "react";
import GlobalStyles from "./components/styles/Global";
import darkTheme from "./components/styles/darkTheme";
import lightTheme from "./components/styles/lightTheme";
import { ThemeProvider } from "styled-components";
import { createBrowserRouter, RouterProvider } from "react-router-dom";
import HomePage from "./pages/Home";
import HelpPage from "./pages/Help";
import NavigationBar from "./components/NavigationBar";
const router = createBrowserRouter([
{ path: "/", element: <HomePage /> },
{ path: "/help", element: <HelpPage /> },
]);
function App() {
const theme = lightTheme;
return (
<ThemeProvider theme={theme}>
<Fragment>
<GlobalStyles></GlobalStyles>
<NavigationBar></NavigationBar>
<RouterProvider router={router}></RouterProvider>
</Fragment>
</ThemeProvider>
);
}
export default App;
2
Answers
I found a solution, which was to use the "!important" keyword but this is not recommended. But there is another trick: the correct and working solution is to use
<StyledEngineProvider injectFirst>...</StyledEngineProvider>
in the returning JSX code in the App.js. It is also recommended by the official documentation.Another way to achive this is by changing it from theme. You can see in this example.
https://www.brainstormcreative.co.uk/material-ui/how-to-change-the-material-ui-appbar-background-color/