Ad

Material-UI : Pass Props To UseStyles When Using Array.map()

I've done some research on passing props to makeStyles in Material-UI, and this answer has the solution that passes the props as a variable. But it would be nice if I could pass the array values to styles as well. For example, it's not possible to set the url of background image using makeStyles.

const useStyles = makeStyles((theme) => ({
  root: {
    borderRadius: props => props.raidus
    backgroundImage: props => `url(${props.urls[0]})` // failure -- This will set every url to first image
  }
}));

export default App = () = {
  const urls = [
      'path/image-1.jpg', 
      'path/image-2.jpg',
      'path/image-3.jpg',
  ];
  const props = {
    radius: 10,
    urls: urls
  };
  
  const classes = useStyles(props);

  return (
    <div>

    {urls.map((url, index) => {
      <div
        key={index}
        className={classes.root}  // <--- I want it handled here
        // styles={{ background: `url(${url})` }}  // <--- alternative way
      />
    )}

    </div>
  );
};

Alternatively, the url for the background image can be set using inline styles (as shown in the commented-out line), but I would like them to be handled inside the styles in Material-UI. Can this be done inside the class root ? Any help would be appreciated.

Ad

Answer

You need another component that retrieves the url and passes it to useStyles()

const urls = ["path/image-1.jpg", "path/image-2.jpg", "path/image-3.jpg"];

const useStyles = makeStyles(theme => ({
  root: {
    borderRadius: props => props.radius,
    backgroundImage: props => `url(${props.url})`
  }
}));

function MyComponent(props) {
  const { url } = props;

  const styleProps = {
    radius: 10,
    url
  };

  const classes = useStyles(styleProps);

  return (
    <div
      className={classes.root}
    >
      {url}
    </div>
  );
}

export default function App() {
  return (
    <div>
      {urls.map((url, index) => (
        <MyComponent key={index} url={url} />
      ))}
    </div>
  );
}

Working example (check the background-image property from the devtools)

Edit inspiring-hodgkin-x7ctu

Ad
source: stackoverflow.com
Ad