Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to set <Box /> type with styled in MaterialUI

@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?

like image 554
aopanasenko Avatar asked Oct 20 '25 16:10

aopanasenko


1 Answers

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>
  );
}

Edit styled Box with props

like image 66
Ryan Cogswell Avatar answered Oct 23 '25 06:10

Ryan Cogswell