I have a React component with the following files:
- src/components/HomePage/index.js
- src/components/HomePage/style.scss
The component is very simple:
import React from 'react';
import './style.scss';
const HomePage = () => {
return (
<div className="homepage">
<h1>Landing page</h1>
</div>
);
};
export default HomePage;
Within style.scss
I am applying a style to all <h1>
tags:
h1 {
color: #f3f3f3;
font-family: "Cambria";
font-weight: normal;
font-size: 2rem;
}
And it works as expected. However, I now see that the h1 style within styles.scss
is being applied to every h1 on my site, even on pages that do not use this component.
I am using Gatsby, but it's a React app at heart. My understanding is that React's code-splitting feature would take care of this, that the code from style.scss
would only be included in bundles for any page that uses my component.
It's the why that I am asking about. I have two easy fixes:
- Wrap everything in
style.scss
in a.homepage
wrapper - Use CSS modules and rename the file to
style.module.scss
. When I see people do that they always do `import style from './style.module.scss' - is there a way to have CSS modules without assigning it to an object like that?
Update: Coming back to this question after spending a lot of time with React and I think there's a gap in the market for React styling. CSS modules is syntactically poor in my opinion and having to manually wrap everything in a .home
tag to localise it is manual work I don't want to do. Someone should really create a React plugin that automatically does this so that whenever I have a file called Home.js
and I import Home.css
that all the CSS is automatically restricted to Home.js
without me having to do anything special.