I am trying to make a tree table reorderable via drag and drop.
Here's the render for easier visualization:
I am also using React-DnD.
Here's a piece of my code:
const moveRow = useCallback(
(record: StructureElement) => (dragIndex, hoverIndex) => {
// console.log(record.name, dragIndex, hoverIndex);
const dragRow = sortableData[dragIndex];
if (!dragRow) {
console.log(sortableData, dragIndex);
} else {
console.log('drag', dragRow.name, 'hover', sortableData[hoverIndex].name);
}
// todo - change the order in array
},
[sortableData],
);
<StyledTreeTable
components={components}
dataSource={sortableData}
onRow={(record, index) => {
return {
index,
moveRow: moveRow(record as StructureElement),
};
}}
/>
So the problem is, my sortableData looks like this:
[
{ name: 1 },
{ name: 2 },
{
name: 3,
children: [
{ name: 11 },
{ name: 22 },
{ name: 33, children: [{ name: 111 }, { name: 222 }, { name: 333 }] },
],
},
];
So my objects can have more objects nested in children.
But moveRow function doesn't see it this way. For it, ABSTRACT_STATE_4 is of index 4. So when I try to reorder the array, I try to do this: data[4], which results in undefined.
Is there a way I can reorder the items in tree table with drag and drop, that I haven't found yet?
The only way I see of solving it now, is to recreate the array the way hover and drag indexes match. But that's a lot of seemingly unnecessary work.
Is there a way to get the record I am hovering over, like I'm getting hoverIndex?
Related
I'm a react.js beginner, searching for methods to alter my data structure. For example, I want to push new objects into the children-array or remove them by key.
What is the appropriate way to do that?
const [treeData, setTreeData] = useState([
{
title: "parent 1",
key: "0-0",
icon: <UserAddOutlined />,
children: [
{
title: "parent 1-0",
key: "0-0-0",
icon: <UserAddOutlined />,
children: [
{
title: "leaf",
key: "0-0-0-0",
icon: <UserAddOutlined />,
},
{
title: "leaf",
key: "0-0-0-1",
icon: <UserAddOutlined />,
},
],
},
{
title: "parent 1-1",
key: "0-0-1",
icon: <UserAddOutlined />,
children: [
{
title: "sss",
key: "0-0-1-0",
icon: <UserAddOutlined />,
},
],
},
],
},
]);
So you should not update the state directly. It is not allowed.
Maybe where you are receiving data from, suppose via api and the data is response.payload.data etc.
So in your case use the setTreeData(response.payload.data) method to add stuff in it.
Now if you want to update certain value (remove or update using index etc). Obviously you will have to have index somehow.
So for deleting say you will have some click and against that a handler for it
removeItem(e) {
item_to_remove = e.target..... etc // to get the item's reference for matching
setTreeData(treeData.filter(items => item.<someproperty> != item_to_remove))
// In your case could also be targetting children maybe
// setTreeData(treeData.Children.filter(items => item.<someproperty> != item_to_remove))
}
I would say maybe handle childrens' array inside another useState variable (childrenTreeData maybe). But you will have to look it's feasibility too. Just an idea after seeing your data
JUST for INFO
This is something similar I did for updating prices inside each cards in my project
const getCurrentPrice = useCallback(() => { // <======= maybe you do not need this
const updatedTilesData = tilesData.map((tile: any) => {
return {
...tile, // <======= get everything here and then update the price below for item
currentPrice: calculateDNCurrentPrice(
tile.startingPrice,
tile.dnTimestamp
),
};
});
setTilesData(updatedTilesData);
}, [tilesData]);
Hey I'm trying to implement nested drag&drop within re-order sequencesin my MERN app. I working to find ideal approach for mongodb data model and implement to Lexicographic order or linked lists for infinite sub folders. I used Model Tree Structures in this link but every node have limitless children for that require recursion and recursive functions or currying. Documentations not clear enough for make do that.
I want show all tree once and not sohuld appear after than click to arrow icon.There is my doodles for front side generation that working with only one depth such like graph nodes. Maybe Modified Preorder Tree Traversal implementation examples you have for this scenario.
const tree = data => { // immutable array
let ascendants = data.filter(d=>d.parent==null)
let descandants = data.filter(d=>d.parent)
**strong text**
let form = []
ascendants.map(a=>{
let node1 = {...a}; /// copying
let node1Children = [];
descandants.map(b=>{
let node2 = {...b};
if(node1._id == b.parent){
node1Children.push(node2)
}
})
node1.children = node1Children;
form.push(node1);
})
return form;
}
I cant take result with using $graphLookup because list format is not what i want.Could you give me some mongodb playground or grouping aggregate solutions? Below json examples shown my expecting results. I can do before but hardcode is unapropriate and performless. Is comparing good way?
[
// mongo database
{_id:123, title:'Books', slug:'books', parent:null },
{_id:124, title:'Programming', slug:'programming', parent:null },
{_id:125, title:'JavaScript', slug:'javascript', parent:'programming' },
{_id:126, title:'C++',slug:'cpp', parent:'programming' },
{_id:127, title:'React', slug:'react', parent:'javascript' },
{_id:128, title:'Redux', slug:'redux', parent:'react' },
{_id:129, title:'Toolkit', parent:'redux' },
{_id:130, title:'Saga', parent:'redux' },
{_id:131, title:'Nodejs', parent:'programming' },
{_id:132, title:'Databases', slug:'databases' },
{_id:133, title:'MongoDB', parent:'databases' },
]
[
// what i want
{ title: "Books"},
{ title: "Programming", parent:"computer-science", children: [
{ title: "JavaScript", children: [
{ title: "React", children: [
{ title: "Redux", children: [
{ title: "Saga" },
{ title: "Thunk" },
{ title: "Mobx" },
{ title: "Observable" },
{ title: "Context" },
{ title: "GraphQL" },
{ title: "Toolkit", children:[
{ title: "typescript" },
{ title: "slices", children:[
{ title: "createAsyncThunk" },
{ title: "createSlice" },
] },
] },
] },
{ title: "Nextjs" },
]},
{ title: "Vue", },
{ title: "angular", },
]},
{ title: "C++", },
{ title: "NodeJS", },
] },
{ title: "MongoDB", parent: "databases"},
]
You could create a Map to key your objects by slug. The values per key will be the result objects for parent objects. Include an entry for null, which will collect the top-level elements.
Then iterate the data again to populate children arrays -- when that property does not exist yet, create it on the fly. Finally output the top-level elements.
function makeTree(data) {
let children = []; // Top-level elements
let map = new Map(data.map(({title, slug}) => [slug, { title }]))
.set(null, {children});
for (let {slug, parent, title} of data) {
(map.get(parent || null).children ??= [])
.push(slug ? map.get(slug) : {title});
}
return children;
}
// Your mongodb data:
const data = [{_id:123, title:'Books', slug:'books', parent:null },{_id:124, title:'Programming', slug:'programming', parent:null },{_id:125, title:'JavaScript', slug:'javascript', parent:'programming' },{_id:126, title:'C++',slug:'cpp', parent:'programming' },{_id:127, title:'React', slug:'react', parent:'javascript' },{_id:128, title:'Redux', slug:'redux', parent:'react' },{_id:129, title:'Toolkit', parent:'redux' },{_id:130, title:'Saga', parent:'redux' },{_id:131, title:'Nodejs', parent:'programming' },{_id:132, title:'Databases', slug:'databases' },{_id:133, title:'MongoDB', parent:'databases' }];
console.log(makeTree(data));
Now before you mark this question as duplicate, hear me out.
i have a json response in reactjs that goes like
organisationUnits: [
{
name: "0.Mzondo",
id: "nW4j6JDVFGn",
parent: {
id: "Ppx2evDIOFG"
}
},
{
name: "1 Chipho",
id: "eE4p4gXpR4p",
parent: {
id: "JKNTgsOVMOo"
}
}, {}, {}, ....
}]
now I have searched the net for a list-to-tree solution i've a lot of code from people but it doesn't seem to work.
Ive also tried https://github.com/yi-ge/js-tree-list and https://www.npmjs.com/package/list-to-tree and also https://www.npmjs.com/package/array-to-tree
but nothing works, i assume its because my parent id is trapped in the parenthesis. So nothing online works. If anyone has a solution to this, it'd be greatly appreciated.
Okay for all those that may get stuck in the future, here's how i solved the issue.
surprisingly I'm not very bright, so wrong career choice.... here goes
var arrayToTree = require('array-to-tree');
var array = [
{
name: "0.Mzondo",
id: "nW4j6JDVFGn",
parent: {
id: "Ppx2evDIOFG"
}
},
{
name: "1 Chipho",
id: "eE4p4gXpR4p",
parent: {
id: "JKNTgsOVMOo"
}
}, {}, {}, ....
}
array.map((item) => {
//
if(item.parent != null){
//console.log(item.parent.id)
item.parent = item.parent.id
} else {
item.parent = undefined
}
});
var tree = arrayToTree(array, {
parentProperty: 'parent',
customID: 'id'
});
console.log( tree );
this.setState({
orgUnits : tree
});
done.
Thank you so much to all those that helped. like really
First of all i am very new to React JS. So that i am writing this question. I am trying this for three days.
What I have to do, make a list of category, like-
Category1
->Sub-Category1
->Sub-Category2
Categroy2
Category3
.
.
.
CategoryN
And I have this json data to make the listing
[
{
Id: 1,
Name: "Category1",
ParentId: 0,
},
{
Id: 5,
Name: "Sub-Category1",
ParentId: 1,
},
{
Id: 23,
Name: "Sub-Category2",
ParentId: 1,
},
{
Id: 50,
Name: "Category2",
ParentId: 0,
},
{
Id: 54,
Name: "Category3",
ParentId: 0,
},
];
I have tried many open source examples, but their json data format is not like mine. so that that are not useful for me. I have build something but that is not like my expected result. Here is my jsfiddle link what i have done.
https://jsfiddle.net/mrahman_cse/6wwan1fn/
Note: Every subcategory will goes under a category depend on "ParentId",If any one have "ParentId":0 then, it is actually a category, not subcategory. please see the JSON
Thanks in advance.
You can use this code jsfiddle
This example allows to add new nested categories, and do nested searching.
code with comments:
var SearchExample = React.createClass({
getInitialState: function() {
return {
searchString: ''
};
},
handleChange: function(e) {
this.setState({
searchString: e.target.value.trim().toLowerCase()
});
},
isMatch(e,searchString){
return e.Name.toLowerCase().match(searchString)
},
nestingSerch(e,searchString){
//recursive searching nesting
return this.isMatch(e,searchString) || (e.subcats.length && e.subcats.some(e=>this.nestingSerch(e,searchString)));
},
renderCat(cat){
//recursive rendering
return (
<li key={cat.Id}> {cat.Name}
{(cat.subcats && cat.subcats.length) ? <ul>{cat.subcats.map(this.renderCat)}</ul>:""}
</li>);
},
render() {
let {items} = this.props;
let {searchString} = this.state;
//filtering cattegories
if (searchString.length) {
items = items.filter(e=>this.nestingSerch(e,searchString))
console.log(items);
};
//nesting, adding to cattegories their subcatigories
items.forEach(e=>e.subcats=items.filter(el=>el.ParentId==e.Id));
//filter root categories
items=items.filter(e=>e.ParentId==0);
//filter root categories
return (
<div>
<input onChange={this.handleChange} placeholder="Type here" type="text" value={this.state.searchString}/>
<ul>{items.map(this.renderCat)}</ul>
</div>
);
}
});
Hello I have the following JSONs
$scope.Facilities=
[
{
Name: "-Select-",
Value: 0,
RegionNumber: 0
},
{
Name: "Facility1",
Value: 1,
RegionNumber: 1
},
{
Name: "Facility2",
Value: 2,
RegionNumber: 1
},
{
Name: "Facility3",
Value: 3,
RegionNumber: 2
}
];
$scope.Regions=
[
{
Name: "-Select-",
RegionNumber: 0
},
{
Name: "USA",
RegionNumber: 1
},
{
Name: "Mexico",
RegionNumber: 2
}
];
I would have two DropdownLists in my app which will have one of these Jsons assigned to it.
Whenever you select a Region, a ng-change would be triggered. What I want, is to make the Facility DDL to update it's values. It would only show the Facilities which have a RegionNumber equivalent to the selected Region's RegionNumber.
How could I achieve this? I'm using Angular JS, MVC...
Note: The -Select- Value must always appear, even if it's value is zero and is not equivalent to the selected Region.
While a data structure, like greengrassbluesky may simplify the result, you can accomplish the same thing with an onchange that leverages javascript filtering
$scope.Facilities = masterFacilities.filter(function (el) {
return regionNumber = el.RegionNumber == $scope.SelectedRegion || el.RegionNumber == 0;
});
Here's a fiddle with an example using your lists.
I think you need a data structure like below:
$scope.Regions=
[
{
Name: "-Select-",
facilities : {
facilityId: 1,
facilityName: "facility1"
},
{
facilityId: 2,
facilityName: "facility2"
}
},
{
Name: "USA",
facilities : [{
facilityId: 1,
facilityName: "facility1"
},
{
facilityId: 2,
facilityName: "facility2"
}]
},
];
So, you could reference them like below:
For the dropdown of Regions, you can iterate through above Data structure.
Store the selectedRegion in selectedRegion
Then use that for the dropdown for facilities.