Fox Fox - 3 months ago 7
React JSX Question

Using props to toggle nav list, with nested array/object

I have two components that are loading some data. What I want is for the links to output like this:


  • group1

    linka linkb



But it's doing this


  • group1

    linka

  • group1

    linkb



I can understand it is to do with the use of my maps and how i am returning the data but I cant figure out how to fix it and keep the click handler working for the groups.

const navList = [
{
"GroupName": "group1",
"links": [
{"name": "link0a","id": "434"},
{"name": "link0b","id": "342"}
]
},
{
"GroupName": "group2",
"links": [
{"name": "link1a","id": "345"},
{"name": "link1b","id": "908"}
]
}
]

class Nav extends Component {

constructor(props) {
super(props);
this.state = {
openItem: null
}

this.toggleClick = this.toggleClick.bind(this);
}

toggleClick(item, index, event) {
event.preventDefault()
if (index === this.state.openItem) {
this.setState({openItem: null})
} else {
this.setState({openItem: index})
}
}

render() {
return (

<ul>
{navList.map((section, i) => {
const links = section.links.map((item, index) => {
const isOpen = this.state && this.state.openItem === index

return <NavItem title={section.GroupName} children={item.name} onClick={this.toggleClick.bind(null, item, index)} open={isOpen} />
})

return links
})}
</ul>

)
}
}

class NavItem extends Component {
render() {
const toggleClass = this.props.open ? 'is-open' : ''
return (
<li>
<h2 onClick={this.props.onClick}>{this.props.title}</h2>
<ul className={toggleClass}>
<li>{this.props.children}</li>
</ul>
</li>
)
}
}

export default NavItem

leo leo
Answer

Remove {this.props.title} from NavLink and move it in your render() function that you posted above. Otherwise, every time you render a NavLink, the title would be shown. Don't forget to move your onClick handler also.

Here is a working example based on your jsfiddle: https://jsfiddle.net/lustoykov/n21Lspm3/