10

I have created a UI from my JSON data in react, where I am creating tab and nested some elements in each tab which is working fine.

I have a delete button for each tab so when I click delete it is removing that particulate tab.

I am also nesting elements inside my tabs, so now I am trying to delete those elements on click of the corresponding button, but I am getting an error.

To create new tab I am doing this:

      const addNewTab = () => {
        const name = window.prompt("Enter Name");
        if (name) {
          setData((data) => [...data, new Data(id, name)]);
        }
      };

And to create new elements inside that tab:

      const Create_element = () => {
        const data_name = window.prompt("Enter Data Name");;
        if (data_name ) {
          setData((data) =>
            data.map((el, i) =>
              i === active_menu
                ? {
                    ...el,
                    myData: [...el.myData, { data_name,  }]
                  }
                : el
            )
          );
        }
      };

To delete the tab:

    setData((data) => data.filter((_, i) => i !== index));

  const deleteData = (index) => {
    console.log("delete", index);
    setData((data) =>
      data.map((dataItem, dataIndex) =>
        dataIndex === active_menu
          ? {
              ...data[dataIndex],
              myData: data[dataIndex].myData.filter((_, i) => index !== i)
            }
          : dataItem
      )
    );
  };

Edit / Update

I just want to edit the name of tab as well as the name of my nested elements name.

Code Sandbox I have added delete functionality, now just want to edit Tab name and elements name inside each tab

Edit / Update

How can I update the name of particular element inside the tabs

3 Answers 3

1

create json like :

const tabJSON = {"home":"<element>","contact":"<element", ...}

assign that to state in hooks :

const [tab, setTab] = useState(tabJSON);

onClick pass key like:

onClick={()=>handleClick(key)}

in handleClick update tab

handleClick=param=>{
   const updatedTab = {...tab};
   if(param in tab){
     delete updatedTab[param]; //remove updated tab and its content
 }
    setTab(updatedTab); 
}

for update Tab:

const handlEditTab=(index,tabName)=>{
    const newTabName = prompt(`Rename ${tabName}`);
    /**
     * here any layover form can be used or any condition also can be put for tab name
     */
    if(tabName){
      const newTabs = [...data];
      const indexOfElement = newTabs.findIndex(obj=>obj.id===index);
      newTabs[indexOfElement].name= newTabName;
      setData(newTabs)
    }
  }

in JSX call this function like given:

...
<div onDoubleClick={()=>handlEditTab(li.id,li.name)} className="dashboard_name col-10 col-sm-10 col-md-9 col-lg-10 col-xl-10">
...

here is the working example. here I used double click to update and single click to select, you can update it accordingly as per requirement.

Sign up to request clarification or add additional context in comments.

7 Comments

I canot change the data, this is what I am getting from server end, i think I am missing something in my own code
assign response of the server to another variable and then you can edit it, consider ‘tab’ as response from server.
please check my edit, I have added dlete functionality, now I just want to add edit the name of tab and elements
hey, updated the answer, hopefully this will workout for you.
Hey here I can only edit tab name, how can I edit the elements names also which is inside the tabs
|
0

When you are mapping over items (or subitems) it is best practice to have a unique key for each item in the map. This key should not be the index in the array as this could change (i.e. on a delete). With a unique key React can manage the state properly and it will also help you edit the according item (or subitems).

I've added a unique_id property to your subitems (myData).

data1 = [
  {
    id: 1,
    name: "Maxi",
    myData: [
      {
        unique_id: "61225_wsadfig",
        data_name: "div1",
        data_title: "div1 tittle"
      },
      ... etc.
]

I suggest using a unique id library like uuid to generate these values.

Then, whenever you add a new item you can set the unique_id with uuid().

const Create_element = () => {
    const data_name = window.prompt("Enter Data Name");
    const data_title = window.prompt("Enter Data Title");

    if (data_name && data_title) {
      setData((data) =>
        data.map((el, i) =>
          i === active_menu
            ? {
                ...el,
                myData: [
                  ...el.myData,
                  { data_name, data_title, unique_id: uuidv4() }
                ]
              }
            : el
        )
      );
    }
  };

Finally, to edit the value of your element in question: pass a editData function as a prop like you do with your deleteData function.

I used an <input/> to record the new value of the users input. With an input make sure you set the name property of the input to this new unique_id. This will lead you to being able to match the unique_id with the input in question like so:

  const editData = (e, index) => {
    const dataName = e.currentTarget.name;
    const newValue = e.currentTarget.value;

    setData((data) =>
      data.map((dataItem, dataIndex) => {
        return {
          ...dataItem,
          myData: dataItem.myData.map((x, i) => {
            if (x.unique_id === dataName) {
              return {
                ...x,
                data_title: newValue
              };
            }
            return x;
          })
        };
      })
    );
  };

Here is a working sandbox.

Comments

0

You can alter your elements pretty similar as you've done with your delete functionality but instead use map function

So in order to rename your tab you can map through your whole collection, and if item has matching index, update it's name, otherwise just return same item:

const renameTab = (index) => () => {
    const newName = window.prompt("Enter New Name");
    if (newName) {
      setData(data => data.map((dataItem, idx) => {
        if (index === idx) {
          return {
            ...dataItem,
            name: newName
          }
        }

        return d;
      }));
    }
}

Here is sandbox with ability to rename tab/element and remove tab/element - please note that "E" button is to initiate edit.

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.