Home > Software design >  Problem with refreshing part of component
Problem with refreshing part of component

Time:04-02

Hello I've got a problem with refreshing component, it doesn't work, in console log shows properly data. I want after click on div to change clicked element on true and add to this element changed class name

below is jsx

{tabObjects.map((item) => (
            <div
              key={item.key}
              id={item.key}
              className={item.isChecked ? checked : notChecked}
              onClick={() => selectItem(item.key)}
            >
              <i className={item.icon}></i>
              <p className="hide-sm">{item.pText}</p>
            </div>
          ))}

after clicking selectItem I want to change class name to checked and rest of them set checked as false so:

const selectItem = (e) => {
    tabObjects.map((item) => {
      item.isChecked = false;
      if (e === item.key) {
        item.isChecked = true;
      }
    });
    setTabObjects(tabObjects);
  };

and sample data json

    const [tabObjects, setTabObjects] = useState([
    {
      key: "sample1",
      isChecked: true,
      icon: "sample1i",
      pText: "Test text",
    },
    {
      key: "sample2",
      isChecked: false,
      icon: "sample2i",
      pText: "Test text",
    },
   
  ]);

let checked = "sampleClass checked";
  let notChecked = "sampleClass";

What Am I doing wrong? Clicking on any div with console log working fine

CodePudding user response:

Missing return statement is the reason.

const selectItem = (e) => {
  const objects = tabObjects.map((item) => {
    item.isChecked = false;
    if (e === item.key) {
      item.isChecked = true;
    }
    return item;
  });
  setTabObjects(objects);
};
  • Related