Saurabh
Saurabh

Reputation: 1672

Passing props to makeStyles react

I have this component

 const MyComponent = (props) => {
  const classes = useStyles(props);

  return (
    <div
      className={classes.divBackground}
      backgroundImageLink={props.product?.image}
      sx={{ position: "relative" }}
    ></div>
  );
};


export default MyComponent;

I am trying to pass backgroundImage link in props and trying to put into makeStyles

export default makeStyles(props => ({
    divBackground:{
        background:`url("${props.backgroundImageLink}")`,
    }
}));

But this does not works

& I am getting this warning in console

index.js:1 Warning: React does not recognize the `backgroundImage` prop on a DOM element. If you intentionally want it to appear in the DOM as a custom attribute, spell it as lowercase `backgroundimage` instead. If you accidentally passed it from a parent component, remove it from the DOM element.

Upvotes: 2

Views: 3024

Answers (2)

NearHuscarl
NearHuscarl

Reputation: 81823

You're not supposed to pass arbitrary attributes to the native elements (div in this case) because it doesn't do anything. The prop only works when passed in useStyles:

export default makeStyles({
  divBackground: {
    background: props => `url("${props.product?.image}")`,
  }
});

Usage

 const MyComponent = (props) => {
  // you only need to pass the props here. useStyles will then use the
  // prop.product.image to create the background property, generate a
  // stylesheet and return the class name for you.
  const classes = useStyles(props);

  return (
    <div
      className={classes.divBackground}
      // remove this line -----> backgroundImageLink={props.product?.image}
      sx={{ position: "relative" }}
    ></div>
  );
};

Upvotes: 2

Samira
Samira

Reputation: 2753

    const MyComponent = (props) => {
  const classes = useStyles(props)();

  return (
    <div
      className={classes.divBackground}
      backgroundImageLink={props.product?.image}
      sx={{ position: "relative" }}
    ></div>
  );
};


export default MyComponent;

then :

export default useStyles=(props)=>makeStyles(()=> ({
    divBackground:{
        background:`url("${props.backgroundImageLink}")`,
    }
}));

Upvotes: 1

Related Questions