Bilawal Wajid Ali
Bilawal Wajid Ali

Reputation: 264

Icon in material UI button

I am new to react therefore I stuck with one thing and that is , I have delete icons injected in buttons and have multiple buttons on the front-end side, I want when any of the visible button clicked only that specific button can be deleted or disappear and remaining untouched buttons can still be visible on the front end page.

Any leads?

here is the sample code : https://codesandbox.io/s/reactjs-simple-conditional-rendering-example-gocg0

Thanks

Upvotes: 1

Views: 7656

Answers (1)

Istvan Szasz
Istvan Szasz

Reputation: 1567

You can not store the open state of multiple buttons with a single bool.

You could use a list to store the displayed buttons:

const [openButtons, setOpenButtons] = React.useState([
  "Computer Science",
  "Business Adminstration",
  "Business Adminstration",
  "Media Studies",
  "Human Resources",
  "Udemy"
]);

Change the handleClose function to filter out the deleted item from the list:

function handleClose(buttonName) {
  setOpenButtons(
    openButtons.filter(openButtonName => openButtonName !== buttonName)
  );
}

And display the buttons if they are present in the stored list:

{openButtons.includes("Computer Science") && (
  <Button
    variant="contained"
    color="primary"
    className={classes.button}
    onClick={() => handleClose("Computer Science")}
  >
    Computer Science
    <DeleteIcon className={classes.rightIcon} />
  </Button>
)}

Here's the codesandbox example.

Upvotes: 2

Related Questions