Introduction
In writing micro front-ends (MFEs), I've made heavy use of styled-components to easily scope my CSS to just the single MFE that I'm working on to help avoid style collisions with both other MFEs on the same page as well as the legacy applications that integrate the apps that I'm writing.
This went swimmingly for both my custom components in my component library as well as the components my team chose as a base (bootstrap-styled).
Styling Someone Else's Component
But when it came time to start using third-party components that shipped their own CSS along with their components, I became worried.
Thankfully, styled-components
handles this situation gracefully. You simply need to be able to pass a className
prop to the component you are trying to target. And if that specific component does not accept that prop, you can get around that by creating a higher-order component that just has a wrapping div with the className
passed to it.
This is exactly what I had to do with Draft.js:
With that className
prop, styled-components
was able to do its magic and make my Draft.js
instance look exactly how I needed to without leaking any styles to the rest of the page by creating CSS rules that only took effect within the context of the randomly generated class name that styled-components
gave that wrapper div.
So, CSS like this placed into a styled-component
definition:
...still produced a normal-looking rich-text area that was micro front-end ready. Allowing me to not worry about the importing the CSS file from Draft.js
.
This strategy works for any component that has known class names that you can target, making it a viable solution for most third-party components out there.
Top comments (0)