Suppose I have a react function with props active
.
// About Page
export default function About() {
return <Menu active="about" />;
}
// Menu Component
function Menu(props) {
const items = ["home", "about", "services", "contact"];
return (
<nav>
{items.map((item, index) => {
console.log(props);
return <li className={`${props.active === item && "active"}`}> {item} </li>;
})}
</nav>
);
}
How do I get the props.active
inside the map() function? it's returning undefined
right now.
Converted to snippet, Seems props is getting correctly. (not related, but minor fix, if you use &&
in class name generation, for the falsy condition classname will be "false")
function About() { return <Menu active="about" />; } function Menu(props) { const items = ["home", "about", "services", "contact"]; return ( <nav> {items.map((item, index) => { console.log(props); return ( <li className={`${props.active === item? "active": "inactive"}`}> {item} </li> ); })} </nav> ); } ReactDOM.render(<About />, document.getElementById('app'))
.active { color: red }.inactive { color: grey }
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script> <div id="app"> </div>
The above sample code in question works flawlessly.
In my project, I was actually modifying the wrong page to provide props, thus got {}
So, I'm writing this answer so that other people won't spend time on it.
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.