I have Created a toggled navigation in React APP. Everything working fine except the toggle. Below is the code of toggle. I am using the check of parentId if parentId exist then include the children id's and it will open the toggle. If not exist then add the main Id which one is parentId in children.
Problem is I parentId already exist and if I click the toggle it is not closing the old one and displaying the new one along with old.
const handleArrowClick = ( data: CoursesNav ) => {
const { id, parentId } = data;
let newtoggledMenus = [...toggledMenus];
if( parentId && newtoggledMenus.includes(parentId)){
if (newtoggledMenus.includes(id)) {
var index = newtoggledMenus.indexOf(id);
if (index > -1) {
newtoggledMenus.splice(index, 1);
}
} else {
newtoggledMenus.push(id);
}
settoggledMenus(newtoggledMenus);
}else{
settoggledMenus([id]);
}
};
I have created the nav structure given below in which under the main item children are added.
export const CourseMenu = ( book: Book ): CoursesNav[] => {
if( course ){
// Chapters from book
return book.chapters.map( c => {
return {
id: c.id,
name: c.name,
link: `/my-book/${course.id}/chapter/${c.id}/edit`,
parentId: c.id,
// get topics and put under children
children: c.topics.map( m => {
return {
id: m.id,
name: m.name,
link: `/my-book/${course.id}/chapter/${c.id}/topics/${m.id}/edit`,
parentId: c.id,
//get blocks and put under blocks
children: m.blocks.map( b => {
return {
id: b.id,
name: b.title,
link: `/my-book/${course.id}/chapter/${c.id}/topics/${m.id}/block/${b.id}/edit`,
parentId: m.id
}
})
}
})
}
});
}
}
Nav logic is added just to show you that what I am trying to create. Every parent has button for toggle to show the sub items. If any sub item has children again the toggle will displayed.
Only I have the problem in opening and closing the correct toggle. Right now under a main children if I open its all child previous one are not closing because they are getting the parentId in toggledMenu state which is a numeric array.