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
Try creating new variable named
newState
with mutated old stateAnd then set state with
newState
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.