Reputation: 6170
Any CSS classnames I write will not override Chakra UI component styles, even when passing them directly as className, ex: <Button className="my-class-that-wont-work">
I created a simple new Chakra-UI project using their CRA guide
npx create-react-app my-app --template @chakra-ui
I proceeded to add a index.css
file and imported it to src/index.js
(or src/App.jsx
) with a simple classname:
.my-class-name {
display: flex;
justify-content: space-between;
}
However, when I try to override any Chakra UI's component styles with a CSS class, the CSS class styles get overriden by Chakra's. Here's a simple example trying to make the Modal Footer have flex + space-between so buttons are spread out.
<ModalFooter className="my-class-name">
This appears to be happening because of how Chakra UI injects it CSS generated with Emotion CSS-in-JS using <style>
tags at the end of <head>
during runtime, which gives Chakra Component CSS authority to override custom CSS imported in JSX components via import "./index.css";
Is there any way to force Chakra UI CSS to be loaded earlier in the <head>
element at runtime so I'm able to override it with normal CSS classes?
Achieving this would not only make it easier for me to implement Chakra UI in an existing codebase, it also allows frameworks like Tailwind CSS relying on utility classes to work properly.
EDIT: It seems like in response to this specific issue, Emotion added support for the "prepend" flag which allows styles tags to be added at the start rather than the end of the selected DOM element where styles are injected. This seems to be a perfect solution to this problem, but I've no idea how to pass that into Chakra UI
Upvotes: 5
Views: 9024
Reputation: 6170
Since Chakra UI uses Emotion CSS as it's styling solution out of the box, I was able to get Chakra UI styles to load earlier in the <head>
instead of at the end by using Emotion's CacheProvider following this thread like so;
import createCache from '@emotion/cache';
import { CacheProvider } from '@emotion/react';
import { ChakraProvider } from '@chakra-ui/react';
const emotionCache = createCache({
key: 'emotion-css-cache',
prepend: true, // ensures styles are prepended to the <head>, instead of appended
});
export default function App() {
return (
<CacheProvider value={emotionCache}>
<ChakraProvider>
</ChakraProvider>
</CacheProvider>
);
}
This solves my problem, but I'm unsure how robust a solution this is as it's not officially documented by the Chakra UI docs. Leaving question open for now in case someone has a better idea on how to implement this.
Upvotes: 7