In the categories.map((category) => () I need to inverse the elements of the categories.map and check for category.isFeatured befor making a link but it doesn’t let me make an if statement.
const Header = () => {
const [categories, setCategories] = useState([])
useEffect(() => {
getCategories().then((newCategories) => setCategories(newCategories))
}, [])
return (
<div className="container mx-auto mb-8 px-10">
<div className="inline-block w-full border-b border-blue-400 py-8">
<div className="block md:float-left">
<span className="cursor-pointer text-4xl font-bold text-white">
<Link href={'/'}>CRBStuffReviews</Link>
</span>
</div>
<div className="hidden md:float-left md:contents">
{categories.map((category) => (
<Link key={category.slug} href={`/category/${category.slug}`}>
<span className="mt-2 ml-4 cursor-pointer align-middle font-semibold text-white md:float-right">
{category.name}
{console.log(category.name)}
</span>
</Link>
))}
</div>
</div>
</div>
)
}
>Solution :
Bravo is right on the Array.reverse in the comments.
You also need to add {} in the .map, check category.isFeatured, and remove any nulls (or you’ll get blank rows).
For example the following will reverse the order, return the link if category.isFeatured, else return null. Finally it will remove all nulls with filter(Boolean) – a nifty trick:
import React, { useState, useEffect } from "react";
const Header = () => {
const [categories, setCategories] = useState([]);
useEffect(() => {
getCategories().then((newCategories) => setCategories(newCategories));
}, []);
return (
<div className="container mx-auto mb-8 px-10">
<div className="inline-block w-full border-b border-blue-400 py-8">
<div className="block md:float-left">
<span className="cursor-pointer text-4xl font-bold text-white">
<Link href={"/"}>CRBStuffReviews</Link>
</span>
</div>
<div className="hidden md:float-left md:contents">
{categories
.reverse()
.map((category) => {
return category.isFeatured ? (
<Link key={category.slug} href={`/category/${category.slug}`}>
<span className="mt-2 ml-4 cursor-pointer align-middle font-semibold text-white md:float-right">
{category.name}
{console.log(category.name)}
</span>
</Link>
) : null;
})
.filter(Boolean)}
</div>
</div>
</div>
);
};