Home > Mobile >  Passing props to makeStyles react
Passing props to makeStyles react

Time:11-18

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.

CodePudding user response:

    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}")`,
    }
}));

CodePudding user response:

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(props => ({
    divBackground:{
        background:`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>
  );
};
  • Related