Issue
The following code snippet grabs items from a list and sorts them alphabetically.
{Object.entries(sortedGroups).sort().map(([groupLetter, groupCities]: [string, any]) => (
<>
<ul className="grid-cols-4 gap-4 float-left inline-block">
<h1>{groupLetter}</h1>
{groupCities.map((city:any) => (
<>
<li key={city.id} className="col-span-1">
<Link to={city.url}>{city.name}</Link>
</li>
</>
))}
</ul>
</>
))}
I would like to arrange the items side by side in four columns like this-
But instead, the above code snippet gives me this-
Any suggestion on how to fix it, please?
Solution
Consider wrapping the .map()
in an element that defines a grid layout. We apply:
display: grid
, via thegrid
class to set the layout as a grid.grid-template-columns: repeat(4, 1fr)
, via thegrid-cols-4
class to set 4 explicit grid column tracks. This will layout the elements as four columns as per your request.gap: 1rem
, viagap-4
to add spacing between each grid element. I assumed you wanted this by inferring from your attempt.
const Link = ({ children, ...props }) => <a {...props}>{children}</a>
const sortedGroups = {
A: [
{ name: "Alabama", id: "Alabama", url: "Alabama" },
{ name: "Austin", id: "Austin", url: "Austin" },
{ name: "Atlanta", id: "Atlanta", url: "Atlanta" },
{ name: "Anchorage", id: "Anchorage", url: "Anchorage" },
],
B: [
{ name: "Baltimore", id: "Baltimore", url: "Baltimore" },
{ name: "Buffalo", id: "Buffalo", url: "Buffalo" },
],
D: [{ name: "Denver", id: "Denver", url: "Denver" }],
F: [{ name: "Florida", id: "Florida", url: "Florida" }],
K: [{ name: "Kansas City", id: "Kansas City", url: "Kansas City" }],
};
function App() {
return (
<div className="grid grid-cols-4 gap-4">
{Object.entries(sortedGroups)
.sort()
.map(([groupLetter, groupCities]) => (
<ul>
<h1>{groupLetter}</h1>
{groupCities.map((city) => (
<li key={city.id}>
<Link to={city.url}>{city.name}</Link>
</li>
))}
</ul>
))}
</div>
);
}
ReactDOM.createRoot(document.getElementById("app")).render(<App />);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdn.tailwindcss.com/3.4.0"></script>
<div id="app"></div>
Answered By - Wongjn
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.