Home > OS >  How to change background color of specific grid/div in MUI in react js from multiple div/grid
How to change background color of specific grid/div in MUI in react js from multiple div/grid

Time:12-04

Hi i want to change color of Grid clicked . I have tried but unfortunately it is changing background color of all the grids. Here is my code . i am trying to handle this through state but can't change color of specific or clicked div

import React, { useState } from "react";
import { DragDropContext, Draggable, Droppable } from "react-beautiful-dnd";
import { styled } from "@mui/system";
import { Container, Grid } from "@mui/material";

const Index = () => {
  const listItems = [
    { id: "1", label: "5,018", text: "Attendence" },
    { id: "2", label: "45%", text: "First time entries" },
    { id: "3", label: "55%", text: "Returning attendees" },
    { id: "4", label: "12", text: "Events Organised" },
  ];
  const [dragDropList, setDragDropList] = useState(listItems);
  const [clicked, setClicked] = useState(false);
  const toggleClicked = (ind) => setClicked((prev) => !prev);

  const Heading = styled("div")({
    fontWeight: "500",
    fontSize: "1rem",
    marginBottom: "2%",
  });
  const DragDropListContainer = styled("div")({});
  const ItemCard = styled("div")({
    width: "99%",
    backgroundColor: !clicked ? "#1B2130" : "#1036fc",

    borderRight: "0.7px solid Grey",
    borderBottom: "0.7px solid Grey",
    display: "flex",
    flexDirection: "column",
    height: "100%",
    alignItems: "center",
    padding: "5% 0 5% 0",
    justifyContent: "center",

    position: "relative",
  });
  const Symbol = styled("div")({
    color: "#ced6e0",
    fontSize: "1.3rem",
    position: "absolute",
    top: "5px",
    right: "5px",
  });
  const UpperHeading = styled("div")({
    fontSize: "2.2rem",
    fontWeight: "bolder",
    color: "#fff",
  });
  const Label = styled("div")({
    fontSize: "0.9rem",
    fontWeight: "500",
    color: "#FFFFFF",
    marginTop: "0.4rem",
    opacity: "0.3",
  });

  const onDragComplete = (result) => {
    if (!result.destination) return;

    const arr = [...dragDropList];

    let removedItem = arr.splice(result.source.index, 1)[0];
    arr.splice(result.destination.index, 0, removedItem);
    setDragDropList(arr);
  };
  return (
    <React.Fragment>
      <Container maxWidth="false">
        <Heading style={{}}>Metric Count</Heading>
        <DragDropContext onDragEnd={onDragComplete}>
          <Droppable droppableId="drag-drop-list" direction="horizontal">
            {(provided, snapshot) => (
              <DragDropListContainer
                {...provided.droppableProps}
                ref={provided.innerRef}
              >
                <Grid container>
                  {dragDropList.map((item, index) => (
                    <Draggable
                      key={item.id}
                      draggableId={item.label}
                      index={index}
                    >
                      {(provided) => (
                        <Grid
                          onClick={toggleClicked}
                          item
                          xs={12}
                          sm={12}
                          md={6}
                          lg={3}
                        >
                          <ItemCard
                            ref={provided.innerRef}
                            {...provided.draggableProps}
                            {...provided.dragHandleProps}
                          >
                            <Symbol>icon</Symbol>
                            <UpperHeading>{item.label}</UpperHeading>

                            <Label>{item.text}</Label>
                          </ItemCard>
                        </Grid>
                      )}
                    </Draggable>
                  ))}
                </Grid>

                {provided.placeholder}
              </DragDropListContainer>
            )}
          </Droppable>
        </DragDropContext>
      </Container>
    </React.Fragment>
  );
};

export default Index;
i am attaching screen shot of ui

Mui Grid Pic

Hi i want to change color of Grid clicked . I have tried but unfortunately it is changing background color of all the grids. Here is my code . i am trying to handle this through state but can't change color of specific or clicked div

CodePudding user response:

const listItems = [
  { id: "1", label: "5,018", text: "Attendence" },
  { id: "2", label: "45%", text: "First time entries" },
  { id: "3", label: "55%", text: "Returning attendees" },
  { id: "4", label: "12", text: "Events Organised" },
];
const [dragDropList, setDragDropList] = useState(listItems);
const [clicked, setClicked] = useState({}); // Initialize the clicked state to an empty object

const toggleClicked = (ind) => {
  setClicked((prev) => ({ ...prev, [ind]: !prev[ind] })); // Update the clicked state with the id of the clicked grid
};

// ...

<Grid container>
  {dragDropList.map((item, index) => (
    <Grid key={item.id} item xs={12} sm={6} md={4}>
      <ItemCard
        onClick={() => toggleClicked(item.id)} // Pass the id of the grid to the toggleClicked function
        style={{
          backgroundColor: clicked[item.id] ? "#1036fc" : "#1B2130", // Use the clicked state to determine the color of the grid
        }}
      >
        <UpperHeading>{item.text}</UpperHeading>
        <Label>{item.label}</Label>
      </ItemCard>
    </Grid>
  ))}
</Grid>

By this snippet you can use the id of that grid to determine which grid to update the color of. You can use the map method to iterate over your list of grid items, and use the id property of each item to check if it matches the grid that was clicked. If it does, you can use the toggleClicked function to update the color of that grid.

  • Related