There are several methods to customize styles in React components:
- Utilize props within the styles
- Use props to determine when specific classes should be applied
- Implement customization using
withStyles
When choosing option 3, the styles of the wrapping component will be combined with the original styles, but the CSS classes of the wrapping component will take precedence as they appear later in the <head>
.
Here's an example showcasing all three customization approaches:
NewComponent.js
import React from "react";
import { withStyles } from "@material-ui/core/styles";
const styles = {
root: props => ({
backgroundColor: props.rootBackgroundColor
? props.rootBackgroundColor
: "green"
}),
inner: props => ({
backgroundColor: props.innerBackgroundColor
? props.innerBackgroundColor
: "red"
})
};
const NewComponent = ({ classes, children, hideInnerDiv = false }) => {
return (
<div className={classes.root}>
Outer div
{hideInnerDiv && <div>{children}</div>}
{!hideInnerDiv && (
<div className={classes.inner}>
Inner div
<div>{children}</div>
</div>
)}
</div>
);
};
export default withStyles(styles)(NewComponent);
index.js
import React from "react";
import ReactDOM from "react-dom";
import { withStyles } from "@material-ui/core/styles";
import NewComponent from "./NewComponent";
const styles1 = theme => ({
root: {
backgroundColor: "lightblue",
margin: theme.spacing(2)
},
inner: {
minHeight: 100,
backgroundColor: "yellow"
}
});
const Customization1 = withStyles(styles1)(NewComponent);
const styles2 = {
inner: {
backgroundColor: "purple",
color: "white"
}
};
const Customization2 = withStyles(styles2)(NewComponent);
function App() {
return (
<div className="App">
<NewComponent>Not customized</NewComponent>
<Customization1>Customized via withStyles 1</Customization1>
<Customization2>Customized via withStyles 2</Customization2>
<NewComponent rootBackgroundColor="lightgrey" hideInnerDiv>
Customized using props
</NewComponent>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
https://codesandbox.io/s/styling-reusable-component-5zwis?fontsize=14