Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

433
Views
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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!