I typically use Modernizr to feature-detect for CSS features like flex-box support and fall back to older methods if unsupported:
.mz-flexbox {
// use flex
}
.mz-noflexbox {
// use floats
}
How would one accomplish something similar with styled-components with something like Modernizr where classes are added to the <html> element to indicate feature support?
My only thought at this point is importing components in my "App.js" and using injectGlobal to target them:
import MyComponent from './components/my-component';
injectGlobal`
.mz-flexbox {
${MyComponent} {
// use flex
}
}
`;
It appears @supports would be a sweet solution, but I do care about Internet Explorer, so this is not a solution for this project.
Lastly, I'm not sure if this is a good way to do this, but would something like this work for feature detection? I'm not 100% on what gets compiled with styled-components and what can be calculated at run-time:
styled.div`
${window.Modernizr.flexbox && css`
display: flex;
align-items: center;
`}
`;
Will that work for detection at run-time?
You can just query the classList of the hmtl tag.
const modern = document.querySelector('html').classList
Then just check to see if the feature class you're looking for is in that list. For example:
if (modern.contains('noflexbox') {
// Adjust as per usual
}
It's all just JavaScript :D
A better method, however, would be to use the Modernizr API directly, rather than relying on the presence of classes. So your code would look more like:
if(Modernizr.someFeature) { ... }
Check out the modernizr docs
RE: your last example - yep, that'll work, assuming you're bundling modernizr as a dependency with the rest of your javascript. There are other approaches in the docs for setting up feature tests, which should help reduce condition duplication in your styled strings
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With