'React.Js. Mapping in nested array to update state
In React.js I have array of object:
arr = [
{
type: 'folder',
name: 'src',
id: '1',
files: [
{
type: 'folder',
name: 'name 1',
id: '2',
files: [
{ type: 'file', name: 'JSFile.js', id: '3' },
],
},
{
type: 'folder',
name: 'name 2 ',
id: '6',
files: [
{ type: 'file', name: 'File.js', id: '7' },
{ type: 'file', name: 'JSXfile.jsx', id: '14' },
type: 'folder',
name: 'name 1',
id: '6',
files: [
{ type: 'file', name: 'HTMLfile.html', id: '5' },
],
},
],
},
],
},
]
I have an array of objects, and I want to update this array with some object, for example something like this:
const onAddFile = () => {
const newFile = {
type: 'file',
name: 'SXfile',
id: "100,
}
const folderToPush = files: (1) [{…}],
id: "6",
name: "name 1 ",
type: "folder" <---this is folder which I have selected via click, which I have id of folder and array of files that I have push newFile. and update state instantly.
folderToPush.files.push(newFile)
}
expected output is something like this:
arr = [
{
type: 'folder',
name: 'src',
id: '1',
files: [
{
type: 'folder',
name: 'name 1',
id: '2',
files: [
{ type: 'file', name: 'JSFile.js', id: '3' },
],
},
{
type: 'folder',
name: 'name 2 ',
id: '6',
files: [
{ type: 'file', name: 'File.js', id: '7' },
{ type: 'file', name: 'JSXfile.jsx', id: '14' },
type: 'folder',
name: 'name 1',
id: '6',
files: [
{ type: 'file', name: 'HTMLfile.html', id: '5' },
{ type: 'file', name: 'SXfile.jsx', id: '100' }, <--- here is pushed object
],
},
],
},
],
},
]
I know it have to be some recursive function to map through whole array, but I have no idea how to implement this. Is there a way to make it, with useState only to see changes instantly?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|