ReactJS遍历对象数组渲染报错:Objects are not valid as a React child
Hey there, let's break down why you're seeing this error and how to fix it quickly.
The Root Cause
Your renderLinks variable is an array of <li> React elements, but you're trying to render it directly without wrapping it in a valid parent container. React (even modern versions, which do support returning arrays) still expects valid HTML structure—and <li> elements must be nested inside <ul> or <ol> to follow web standards. This invalid structure is what's triggering the "object not valid as a React child" error.
The Fix
Wrap your renderLinks array in a <ul> container, and let's also fix the active class so only the current page's link is highlighted (right now all links are marked active, which isn't ideal):
// For a class component class Navbar extends React.Component { render() { const links = [ { name: 'How it works', ref: '/' }, { name: 'Calendar', ref: '/calendar' }, // Added leading slash for path consistency { name: 'Contact me', ref: '/contact' } ]; // Get current page path to set active state const currentPath = window.location.pathname; const renderLinks = links.map((link) => ( // Use link.ref as key instead of index (better for React's DOM diffing) <li className={`nav-item ${currentPath === link.ref ? 'active' : ''}`} key={link.ref} > <a className="nav-link" href={link.ref || "#"}> {link.name} </a> </li> )); // Wrap list items in a <ul> to fix structure and React error return ( <ul className="navbar-nav"> {renderLinks} </ul> ); } }
Or for a functional component:
function Navbar() { const links = [ { name: 'How it works', ref: '/' }, { name: 'Calendar', ref: '/calendar' }, { name: 'Contact me', ref: '/contact' } ]; const currentPath = window.location.pathname; return ( <ul className="navbar-nav"> {links.map((link) => ( <li className={`nav-item ${currentPath === link.ref ? 'active' : ''}`} key={link.ref} > <a className="nav-link" href={link.ref || "#"}> {link.name} </a> </li> ))} </ul> ); }
Extra Tips
- Skip using
indexas a key: Since your links have uniquerefvalues, use those instead—this helps React update the DOM more efficiently when your link list changes. - Consistent path formatting: Leading slashes on your
refvalues match the format returned bywindow.location.pathname, making the active state check work reliably. - Stick to HTML standards: Wrapping
<li>elements in a list container avoids both React errors and HTML validation warnings.
内容的提问来源于stack exchange,提问作者Sergey

