0

how to add css in such a way whenever i click and select on div the border and background colors of the div should be changed same goes for all for the selected and should be back to previous if deselected.

This is a seemingly stupid question, but I'm not a pro when it comes to css. I have created a multiple div for multiple selection of div, but the css file that came with it has completely changed the look of it and it looks different to my other controls - Is there a simple way of inheriting the look of another control?

codesanbox

I tried this way

const data = [
  {
    key: 1,
    value: "four"
  },
  {
    key: 2,
    value: "fours"
  }
];

export default function App() {
  const initialState = data.map((item) => {
    return { ...item, selected: false };
  });
  const [work, setWork] = React.useState(initialState);
  const [state, setState] = React.useState();
  const [selected, setSelected] = React.useState("");

  console.log("work");
  console.log(work);
  console.log("work");
  console.log("state");
  console.log(state);
  console.log("state");

  React.useEffect(() => {
    setState(
      work.filter((person) => person.selected).map((person) => person.value)
    );
    setSelected(
      work.filter((person) => person.selected).map((person) => person.value)
    );
  }, [work]);

  const handleSelect = (value) => {
    console.log("value", value);
    const nextState = work.map((item) => {
      if (item.value === value) {
        return {
          ...item,
          selected: !item.selected
        };
      }
      return item;
    });
    setWork(nextState);
  };
  return (
    <div className="parent">
      {work.map((da) => (
        <div
          className={`child  ${selected === da.value ? "selected" : ""}`}
          onClick={() => handleSelect(da.value)}
        >
          {da.value}
        </div>
      ))}
    </div>
  );
}

1 Answer 1

1

I've done slight modifications in the code. Following code would help you get the desired results.

const handleSelect = (key) => {
  const updatedItems = [];
  
  work.forEach((item) => {
    updatedItems.push ({
      ...item,
      selected: item.key === key
    });
  });

  setWork(updatedItems);
};

return (
     <div className="parent">
      {work.map((da) => (
       <div
        className={`child  ${da.selected ? "selected" : ""}`}
        onClick={() => handleSelect(da.key)}
       >
       {da.value}
     </div>
  ))}
 </div>
);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.