skip to Main Content

How can i toggle isExpanded property on onClick by Id. I’m using React for this project.
Here is my json data structure.

const handleExpandOutlineItem = (id: string) => {}

here is my json data structure.

  {
    id: '1',
    title: 'Introduction to Programming',
    isExpanded: true,
    children: [
      {
        id: '1.1',
        title: 'What is programming?',
        isExpanded: false,
        children: [
          {
            id: '1.1.1',
            title: 'What is programming?',
            isExpanded: false,
            children: [],
          },
          {
            id: '1.1.2',
            title: 'What is programming?',
            isExpanded: false,
            children: [],
          },
        ],
      },
      {
        id: '1.2',
        title: 'Programming languages',
        isExpanded: false,
        children: [
          {
            id: '1.2.1',
            title: 'Programming languages',
            isExpanded: false,
            children: [],
          },
          {
            id: '1.2.2',
            title: 'Programming languages',
            isExpanded: false,
            children: [],
          },
        ],
      },
    ],
  },
]

I tried to use recursion, but I should also update state

2

Answers


  1. Try creating new variable named newState with mutated old state

    const newState = change(oldState);
    

    And then set state with newState

    setState(newState)
    
    Login or Signup to reply.
  2. This is a function which updates item in a tree using an id in an immutable way, which means you can simply pass the data from state to it, and store again in state whatever it returns.

      let data = [
        {
          id: '1',
          title: 'Introduction to Programming',
          isExpanded: true,
          children: [
            {
              id: '1.1',
              title: 'What is programming?',
              isExpanded: false,
              children: [
                {
                  id: '1.1.1',
                  title: 'What is programming?',
                  isExpanded: false,
                  children: [],
                },
                {
                  id: '1.1.2',
                  title: 'What is programming?',
                  isExpanded: false,
                  children: [],
                },
              ],
            },
          ],
        },
      ];
    
      let flipIsExpanded = (id, tree) => {
        return tree.map((x) => {
          if (x.id === id) {
            return { ...x, isExpanded: !x.isExpanded };
          }
    
          if (x.children && x.children.length) {
            return { ...x, children: flipIsExpanded(id, x.children) };
          }
    
          return x;
        });
      };
    
      console.log(flipIsExpanded('1.1', data));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search