Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding sx prop to custom component

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?

like image 401
Matthew Kwong Avatar asked Jun 15 '26 23:06

Matthew Kwong


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

like image 179
NearHuscarl Avatar answered Jun 18 '26 14:06

NearHuscarl


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;
like image 31
Garrett Avatar answered Jun 18 '26 13:06

Garrett