One
Two
Three
import { For } from "@chakra-ui/react"
const Demo = () => {
return (
<For each={["One", "Two", "Three"]}>
{(item, index) => <div key={index}>{item}</div>}
</For>
)
}
Usage
The For
component is used to render a list of items in a strongly typed
manner. It is similar to the .map()
.
import { For } from "@chakra-ui/react"
<For each={[]} fallback={...} />
Examples
Object
Here's an example of using the For
component to loop over an object.
Naruto
Powers: Shadow Clone, Rasengan
Sasuke
Powers: Chidori, Sharingan
Sakura
Powers: Healing, Super Strength
import { Box, For, Stack, Text } from "@chakra-ui/react"
const Demo = () => {
return (
<Stack>
<For
each={[
{ name: "Naruto", powers: ["Shadow Clone", "Rasengan"] },
{ name: "Sasuke", powers: ["Chidori", "Sharingan"] },
{ name: "Sakura", powers: ["Healing", "Super Strength"] },
]}
>
{(item, index) => (
<Box borderWidth="1px" key={index} p="4">
<Text fontWeight="bold">{item.name}</Text>
<Text color="fg.muted">Powers: {item.powers.join(", ")}</Text>
</Box>
)}
</For>
</Stack>
)
}
Fallback
Use the fallback
prop to render a fallback component when the array is empty
or undefined.
No items to show
import { For, Stack, VStack } from "@chakra-ui/react"
import { DecorativeBox } from "compositions/lib/decorative-box"
import { LuBox } from "react-icons/lu"
const Demo = () => {
return (
<Stack gap="4">
<For
each={[]}
fallback={
<VStack textAlign="center" fontWeight="medium">
<LuBox />
No items to show
</VStack>
}
>
{(item, index) => (
<DecorativeBox h="10" key={index}>
{item}
</DecorativeBox>
)}
</For>
</Stack>
)
}
Props
Prop | Default | Type |
---|---|---|
each | T[] | readonly T[] | undefined The array to iterate over | |
fallback | React.ReactNode The fallback content to render when the array is empty |