0

I am trying to create the left hand menu like this image for my test application using react, and I am getting the following warning/error at runtime on the browser console when loaded.

index.js:1375 Warning: Each child in a list should have a unique "key" prop. Check the render method of `LeftNav`. See fb.me/react-warning-keys for more information. in Fragment (at LeftNav.js:12) in LeftNav (at App.js:131) in div (at App.js:120) in div (at App.js:118) in div (at App.js:116) in Router (created by BrowserRouter) in BrowserRouter (at App.js:115) in App (at src/index.js:7) 

Each of the navItems props items have distinct IDs, so every component should already have unique keys? Should the React.Fragment have a unique key as well? The LeftNav component is as below

class LeftNav extends Component { render() { return ( <ul> {this.props.navItems.map((navItem) => { return ( <React.Fragment> <LeftNavItem key={navItem.id} navItem={navItem} menuLevel={0} /> {navItem.subMenu.map((subMenuItem) => { return <LeftNavItem key={subMenuItem.id} navItem={subMenuItem} menuLevel={1} /> })} </React.Fragment> ) })} </ul> ) } } LeftNav.propTypes = { navItems: PropTypes.array.isRequired } export default LeftNav; 

LeftNavItem component is as below.

import React, { Component } from 'react' import PropTypes from 'prop-types'; class LeftNavItem extends Component { getClassName = () => { if(this.props.menuLevel === 0) { return 'parent_wrapper'; } else { return ''; } } render() { return ( <li className={this.getClassName()}> <a href="">{this.props.navItem.title}</a> </li> ) } } LeftNavItem.propTypes = { navItem: PropTypes.object.isRequired } export default LeftNavItem; 

The props for LeftNav class is

leftNav: [ { id: 1, title: 'System Admin', active: false, subMenu: [ { id: 2, title: '', active: false }, { id: 3, title: '', active: false }, { id: 4, title: '', active: false }, { id: 5, title: '', active: false }, { id: 6, title: '', active: false }, { id: 7, title: '', active: false }, { id: 8, title: '', active: false }, { id: 9, title: '', active: false } ] }, { id: 10, title: 'Reports', active: false, subMenu: [ { id: 11, title: 'Reports', active: false }, { id: 12, title: 'Dashboard', active: true }, { id: 13, title: 'Templates', active: false } ] 

Thanks!!

2

1 Answer 1

1

Add your key to the fragment instead of the nested tag.

return ( <React.Fragment key={navItem.id}> <LeftNavItem navItem={navItem} menuLevel={0} /> {navItem.subMenu.map((subMenuItem) => { return <LeftNavItem key={subMenuItem.id} navItem={subMenuItem} menuLevel={1} /> })} </React.Fragment> ) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.