I'm new to React and anything other than early 2000's Javascript (hell I'm new to all this UI), and the fact that I'm not finding an answer implies I'm approaching this the wrong way. So I'd appreciate someone showing me the light and/or telling me how to accomplish what I'm trying to do!
In short, I have one component X that has a few instances of another component Y. I'm trying to add css to the parent component that will apply to all of the Ys (specifically, a margin in my use case. Notably, I want to apply this styling only to these instances of Y inside my X, not to every Y on the page. I understand that I can't override specified styles in Y from the parent, but I am trying to add a style that is not specified on Y.
More concretely:
Metrics.js (shortened):
import './Metrics.css'
class Metrics extends Component {
render() {
return (
<div className="Metrics">
<div className="titlebar">
<div>Metrics</div>
<Button>...</Button>
<Button>...</Button>
</div>
</div>
);
}
}
Metrics.css
.titlebar {
...
}
.titlebar Button {
padding: 10px;
}
I believe Button does not work as a selector since that's not the html that actually gets generated. So if Button were a component I owned, and I could modify it to have a root <div className="Button"> then I believe could use
.titlebar .Button {...}
But in this case I am importing Button (from material-ui), so I don't have control over this. I could find out what it happens to render but to my knowledge this is not guaranteed by contract so it would be fragile to depend on that observation.
So is there a way to apply a css selector, or something similar, to a React component by name or some other method of identifying the React component?
I'm looking for a general solution: I don't want to solve this for Button but for any React component I might build or import and use in the same way. E.g. I've already run across the same issue for the FontAwesome component, also imported. Even for components I own, I feel that it's introducing unnecessary tight coupling to depend on a convention that the class on the root element includes the component name. Is there a more generalized and robust way to accomplish this?