Simon Long
Simon Long

Reputation: 1440

Styling a React Material UI Component with a .map function

So I have an array of Material UI components (for my cut down version here I'm using two simple Button components).

How do I add style to these components as I iterate through them in the map function ?

For example how would I adjust the size of the icon to be say 64px x 64px ?

import React from "react";
import "./styles.css";
import Button from "@material-ui/core/Button";
import SaveIcon from "@material-ui/icons/Save";
import DeleteIcon from "@material-ui/icons/Delete";
export default function App() {
  const buttons = [
    <Button
      variant="contained"
      color="primary"
      size="large"
      startIcon={<SaveIcon />}
    >
      Save
    </Button>,
    <Button
      variant="contained"
      color="secondary"
      size="large"
      startIcon={<DeleteIcon />}
    >
      Delete
    </Button>
  ];

  return (
    <div className="App">
      {buttons.map(currButton => {
        //How do I add style to each of these components as I iterate through them ?
        return currButton;
      })}
    </div>
  );
}

Upvotes: 0

Views: 2557

Answers (1)

goto
goto

Reputation: 4425

You need to iterate through an array of functions that take props as argument and return Button components with whatever additional props you pass.

export default function App() {
  const buttons = [
    props => (
      <Button
        variant="contained"
        color="primary"
        size="large"
        startIcon={<SaveIcon />}
        {...props}
      >
        Save
      </Button>
    ),
    props => (
      <Button
        variant="contained"
        color="secondary"
        size="large"
        startIcon={<DeleteIcon />}
        {...props}
      >
        Delete
      </Button>
    )
  ];

  return (
    <div className="App">
      {buttons.map(createButton => {
        const CustomButton = createButton({
          style: { backgroundColor: "red" }
        });
        return CustomButton;
      })}
    </div>
  );
}

Upvotes: 1

Related Questions