I am fairly new to reactjs - in this instance I am looping through json data - with a menu - sub menu nest.
so basically the menu json looks something like this
{
"title": "Dienstleistungen",
"link": "/de/dienstleistungen",
"children" : [
]
},
{
"title": "Beliebte Projekte",
"link": "/de/beliebte-projekte",
"children" : [
{
"title" : "Bundle1",
"link" : "/de/beliebte-projekte/bundle1"
},
{
"title" : "Bundle2",
"link" : "/de/beliebte-projekte/bundle2"
}
]
}
now my issue is the logic for the active state -- currently from parent level this works fine -- so if the current page is /de/dienstleistungen -- the condition currently "item.link === activeLink" is true.
Now I will like to add more logic here to catch the children links if possible so something like this
item.link === activeLink || (item.children.inArray(activeLink))
//code
{
lang.menu.map(function (item, index) {
return (
<li key={index} className={(item.children.length > 0 ? 'has-dropdown' : '')}>
<Link to={item.link} className='headerbar-link-nav'>{item.title}</Link>
{
item.link === activeLink
? <div className='main-nav active' /> : null
}
{
item.children.length > 0
? <ul className='dropdown'>
{item.children.map(subPage => {
return (<li key={subPage.title}>
<Link to={subPage.link}>{subPage.title}</Link>
</li>
)
})}
</ul>
: null
}
</li>
)
})
}
I've just come up with this solution.
const inSubPages = function (obj, activeLink) {
for (var k in obj) {
if (!obj.hasOwnProperty(k)) continue
if (obj[k].link === activeLink) {
return true
}
}
return false
}
let isActive = item.link === activeLink;
item.children.forEach((child)=>{
if(child.link === activeLink){
isActive = true;
}
})
Do this before the return statement inside the map function, and replace you ternary with just isActive && <div className='main-nav active' />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.