I have a Standalone (Reusable) CustomButton
component that imports its own stylesheet (CustomButton.css
). I would like to apply a style to it using className through props, while putting the className styling in my own App.css
.
The following are simplified examples of my code.
CustomButton.js:
import "CustomButton.css";
export default function CustomButton({className=null, children}) {
return (
<button className={"custom-button" + (className? " " + className: ""}>
{children}
</button>
)
};
CustomButton.css
.custom-button {
background: green;
}
App.js:
import "./App.css"
import CustomButton from "./CustomButton";
export default function App() {
return (
<div className="App">
<CustomButton className="app-button">This is app button</CustomButton>
</div>
)
};
App.css
.app-button {
background: red;
}
With the following points in mind:
- Without changing the order of the imports
- Not allowing my App to modify the button through .class
custom-button
(simply because let us say the App doesn’t know). - Without using
!important
- Without using inline styling.
- Specificity doesn’t work here. (I guess)
- Without breaking encapsulation of
CustomButton
component and modifyingCustomButton.css
.
What could be happening now:
The App.js
imports the the App.css
first before importing the CustomButton
. That’s why when I add the className to the CustomButton
component, the CustomButton.css
will still win as according to order of appearance, it came last.
I thank you in advance for any opinions and answers you have.
What I want to happen:
- Make the button’s background red.
What I was able to do:
- Enclosed the CustomButton.css rules in
@layer custom
. This@layer
enclosed the CustomButton’s styling rules into a named layer, which gave it the lowest priority as there were no other layers declared in my app. I don’t know if I’m on the right path here.
Reason why I think this would not work for me:
- This solved it pretty much but I think this is going to break encapsulation. Using layer in a Standalone React Component, will require the App to know more about the Component. Especially the name of the layer that the CustomButton has.
2
Answers
What I would do is, in your CustomButton.jsx I would only apply the .custom-button className if you haven’t defined one as a prop.
This would look like:
You can use inline style prop for additional styling in your component