score:0
doing this recursively is a good way to go about this. what you can do is to give each list item element an onclick
handler.
<li onclick={this._togglechildreninit.bind(this, item.id)}>
i don't know much about what you're id's are like. but consider the following structure:
{id: "0", isopen: false, children: [
{id: "0.0", isopen: false, children: [
{id: "0.0.0", isopen: false, children: null},
{id: "0.0.1", isopen: false, children: null}
]},
{id: "0.1", isopen: false, children: null}
]}
the id for each child is the id of the previous parent, plus a "." and the number of order within that level.
you can then, with recursion, check if the desired item with some x id could be a child of an item, and start traversing that child the same way. this way, you don't have to traverse all items in the tree.
of course, this may vary from application to application, but hopefully it provides a clue of how you could approach this.
the code for the recursion triggered by the click is as follows:
_togglechildreninit = (data_id) => {
var result = this._togglechildren(0, data_id, this.state.listobject);
this.setstate({listobject: result});
}
_togglechildren = (i, data_id, arr) => {
if (i <= arr.length-1) {
if (arr[i].id == data_id && arr[i].children.length > 0) {
arr[i].isopen = !arr[i].isopen;
} else {
var newarr = this._togglechildren(0, data_id, arr[i].children);
arr[i].children = newarr;
if (arr[i].id.charat(0) != data_id.charat(0)) {
arr[i].isopen = false;
}
}
arr = this._togglechildren(++i, data_id, arr);
}
return arr;
}
edit - alternative structure
if your object looks like this:
{id: "0", isopen: false, children: [
{id: "1", isopen: false, children: [
{id: "2", isopen: false, children: null},
{id: "3", isopen: false, children: null}
]},
{id: "4", isopen: false, children: null}
]}
you can use this instead:
_togglechildreninit = (data_id) => {
var result = this._togglechildren(0, data_id, this.state.listobject);
this.setstate({listobject: result});
}
_togglechildren = (i, data_id, arr) => {
if (i <= arr.length-1) {
if (arr[i].id == data_id && arr[i].children.length > 0) {
arr[i].isopen = !arr[i].isopen;
} else {
var newarr = this._togglechildren(0, data_id, arr[i].children);
arr[i].children = newarr;
if (arr[i].id < data_id) {
arr[i].isopen = false;
}
}
arr = this._togglechildren(++i, data_id, arr);
}
return arr;
}
score:4
are you trying to simulate accordion behaviour? if yes then you can modify your code like this. use component's state and toggle it to open and close children. instead of creating <list list={item.children} />
in list
class, import(or use require
) list.js
in list-item.js
and render the child list
item on the basis of current listitem's
state.
list-item.js
class listitem extends react.component {
//add this
constructor (){
super(...arguments);
this.state = { showchild:false};
}
handlecollapse(){
console.log('open/close: ' + this.props.item.display_name);
//add this
this.setstate({showchild:!this.state.showchild});
return false;
}
handlefilter(){
console.log('filter id: ' + this.props.item.id);
return false;
}
render(){
let children;
if(this.state.showchild) {
children = (<list list={this.props.item.children} />);
}
return (
<div>
<a rel="{this.props.item.id}" onclick={this.handlecollapse.bind(this)}>
{this.props.item.display_name}
</a>
<input value="" type="checkbox" onclick={this.handlefilter.bind(this)} />
//add this
{children}
</div>
)
};
}
list.js
class list extends react.component {
render(){
//removed <list .../>, rest is same just other way of doing same stuff
let li = this.props.list.map( (item) => {
return( <li> <listitem key={item.id} item={item} /></li>);
}
);
return ( <ul>{li}</ul>);
}
};
dummy data to test
var data=[
{
id:"1st of level 1",
get display_name(){return _name(this.id,this.children)},
children: [
{
id:"1st of level 1.2",
get display_name(){return _name(this.id,this.children)},
children: [
{
id:"1st of level 1.2.1",
get display_name(){return _name(this.id,this.children)},
children:[]
}
]
},
{
id:"2nd of level 1.2",
get display_name(){return _name(this.id,this.children)},
children:[]
}
]
},
{
id:"2nd of level 1",
get display_name(){return _name(this.id,this.children)},
children:[]
},
{
id:"3rd of level 1",
get display_name(){return _name(this.id,this.children)},
children:[]
},
{
id:"4th of level1",
get display_name(){return _name(this.id,this.children)},
children:[]
}
];
function _name(id,child) {
if(child.length>0)
return("i am "+id+" i have children");
else {
return("i am "+id+" i don't have children ");
}
}
reactdom.render(<list list={data} />,document.getelementbyid('root'));
`
Source: stackoverflow.com
Related Query
- Open and Close a recursively nested list in React js
- Dynamically Open and Close antd / react Collapse Component
- Open menu on mouseover and Close menu on mouseleave in react
- How can I render list items dynamically and recursively from a nested array?
- State to open and close a Dialog in TypeScript in React
- How to open and and close a small window in react passport auth flow
- Embed custom form twice, one instance open and another is close with React js?
- Developing a generic React component to open and close arbitrary forms
- How do I map dispatch to props within a recursively nested component using React and Redux?
- How to open and close an inline dialog in a react redux app
- React Toggle open and close using onclick on map function
- How to update(add and remove) items in redux nested list : Redux, React
- Open and close expandable button in list view
- How to make react router work with static assets, html5 mode, history API and nested routes?
- How to test a component with a nested container with React and Redux?
- Closing React Semantic UI modal with button and close icon
- React and Redux: Managing Redux Custom Middleware List
- Recursively render a deep nested data in React
- React - How to handle nested forms and its value
- Render recursively a nested data in React
- Why memory leak happend and render slowing down when I close and re-open react component (material-table)?
- ant design - Modal value reset on "cancel" and "X" close button - API RESPONSE BASE REACT JS
- React Router v4 and nested routes: index navlink always remain active
- How to open a text file and read the contents from it on react native?
- How to focus a button in a details list using React and Office Fabric
- Material UI (Scrollspy) - React - use tabs to move through list and auto scroll to index
- React router 4 how to nested routes /admin and /
- React Router List and Detail Route at the same time
- React and Material-UI: MuiDialog-root gets stuck after dialog close
- React Router - Open Link on new Tab and Redirect to Home Page
More Query from same tag
- Problem in React typing text in a field text
- React Native rnpm unlink library
- Cannot read property 'handleReset' of undefined
- getting this.props in componentDidMount() or some other way
- cannot get the currentTime of audio on console.log
- React Table removes Filters when updating data
- Original list doesn't show up after a search is made in planets list
- require(variable) causes the error Cannot find module "."
- React Icon component with SVG's
- Unable to send api response data from express to react after refreshing the page
- Performance issue with very fast setState calls in React?
- Warning: Can't perform a React state update on an unmounted component. But I don't have any subscriptions that I know of?
- How to customize material-ui Accordion component behavior/style?
- How to fix JSON parse error: Unexpected indentifier "object" in React Native?
- ReactJS | Cannot convert undefined or null to object (w/ Formik)
- how to declare a react ref in props function when using typescript
- How to implement React in a jQuery-based webapp?
- Ability to specify existing DynamoDB source when adding GraphQL API
- Javascript Map displaying multiple items
- Trustpilot TrustBoxes in Next.js
- Unable to spread an array inside a template literal
- React: how to display success message if all requests were successful in a loop
- Loading a name based on Value from Parent Component Dynamically
- React updating Switch controller State
- Best way to setup a React useReducer
- Check if user completed email verification ReactJS Firebase
- How to edit a json file in react
- ReactJS timestamp
- stylings work even without importing css file in JS files
- SetTimeout Behaving weirdly in ReactJS