@material-ui/styles support next way to redefine default styles:
import React from 'react';
import Box from '@material-ui/core/Box';
import { styled } from '@material-ui/core/styles';
const StyledBox = styled(Box)({
color: 'red'
});
By default Box is like <div /> and I can change it by passing component props:
// somewhere in code
<StyledBox
component="span"
>
Some text
</StyledBox>
And this example doesn't work:
import React from 'react';
import Box from '@material-ui/core/Box';
import { styled } from '@material-ui/core/styles';
const StyledBox = styled(<Box component="span" />)({
color: 'red'
});
Is there a way to make a component definition for Box at the styling stage using styled?
Below is an example showing how to do this. You can't pass <Box component="span" /> (an element) to styled because it is expecting a component type not an element (i.e. an instance of a component). Instead you need to create a new component type (SpanBox in the example below) that wraps Box and passes through any props or ref while specifying the props you want to control (e.g. component="span").
import React from "react";
import Box from "@material-ui/core/Box";
import { styled } from "@material-ui/core/styles";
const StyledBox = styled(Box)({
color: "red"
});
const SpanBox = React.forwardRef(function SpanBox(props, ref) {
return <Box ref={ref} component="span" {...props} />;
});
const StyledSpanBox = styled(SpanBox)({
color: "purple"
});
export default function App() {
return (
<div className="App">
<StyledBox>red div 1</StyledBox>
<StyledBox>red div 2</StyledBox>
<StyledSpanBox>purple span 1</StyledSpanBox>
<StyledSpanBox pl={3} border={1}>
purple span 2
</StyledSpanBox>
</div>
);
}
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