Adding sx prop to custom component

Viewed 1435

I'm using MUI v5, together with Gatsby Image. I'm hoping to keep my styling syntax consistency across the application so I tried to add the sx prop to GatsbyImage.

This is what I've tried:

<Box
  component={GatsbyImage}
  sx={/* my sx styles */}
/>

This does what I want. Yet, I noticed the sx prop somehow gets passed to the img. This ends up getting a <img sx=[object Object]/> in my HTML.

Although this doesn't really affect my application in anyways, I'm wondering are there better ways to achieve this?

2 Answers

You can use the styled function to add the sx prop to your custom component like this:

import { styled } from "@mui/material/styles";

const ComponentWithSx = styled(YourCustomComponent)();
<ComponentWithSx
  sx={{
    width: 30,
    height: 30,
    backgroundColor: "primary.dark"
  }}
/>

When you pass the GatsbyImage to the component prop of Box, GatsbyImage is used as the root component inside Box, and the sx object is passed to the DOM element:

function Box(props) {
  const { component, ...other /* other includes sx prop */ } = props;
  return <component {...other} />;
});

If you want to use Box you need to create a wrapper component to filter the sx prop:

function MyGatsbyImage({ sx, ...props }) {
  return <GatsbyImage {...props} />;
}

Codesandbox Demo

For anyone trying to style a custom component, I did it this way:

Use the materialUI styled function, like so:

import { styled } from '@mui/material/styles';
import Star from '../components/Star'; //my custom component    
[...]
const StarStyled = styled(Star)({ position: 'absolute', right: 5, bottom: 5 });

Then, in your render function, call your newly-styled component:

<StarStyled />

Now, your custom component (in this case, the component "Star") will receive a className prop, so you can use the prop like so:

const Star = ({className}) => {
  
  return (
    <span className={className}>
      ...whatever else you want your component to do
    </span>
  );
};

export default Star;
Related