React Loops work alongside React Hooks as part of the novel React Velcro architecture for building sticky, secure user interfaces that don't come apart under pressure.
yarn add react-loops
Use the props of
to provide the list and as
to provide an element for
each item in the list. The of
prop accepts Arrays, Array-likes,
and Iterables.
<ul>
<For of={myList} as={item =>
<li>{item}</li>
}/>
</ul>
Or provide a "render prop" function as a child.
<ul>
<For of={myList}>
{item =>
<li>{item}</li>
}
</For>
</ul>
Access additional information about each iteration by destructuring the second argument:
index
: A number from 0 to the length of the listlength
: The length of the listkey
: The key for this item in the list. Same asindex
for Arrays but string properties forin
ObjectsisFirst
: True for the first iterationisLast
: True for the last iteration
<ul>
<For of={myList} as={(item, { isLast }) =>
<li><If case={isLast}>and </If>{item}</li>
}/>
</ul>
Use the prop in
to provide an Object instead of an Array or Iterable.
<ul>
<For in={myObj} as={(item, {key}) =>
<li>{key}: {item}</li>
}/>
</ul>
Use the props initial
, condition
, and loop
to have full control over your
loop, as below:
<ul>
<For initial={0} condition={i => i < 5} loop={i => i + 1}>
{i => <li>{i}</li>}
</For>
</ul>
Think of this as you would write a for loop in JavaScript like so:
for (let i=0; i < 5; i++) {
// logic
}
Provide key
on each child to ensure correct behavior if the list may be
reordered over time. If you don't provide key
, the key
of each
iteration will be used by default.
<ul>
<For of={myList} as={item =>
<li key={item.id}>{item.label}</li>
}/>
</ul>
Use the case
prop with <If>
and <ElseIf>
elements to conditionally
include certain elements. When an <If>
case is truthy it does not
render any <ElseIf>
or <Else>
children. However when it is falsey it
only renders <ElseIf>
and <Else>
children.
<If case={someCondition}>
This will only be shown if someCondition is truthy.
<ElseIf case={otherCondition}>
This will only be shown if someCondition is falsey
and otherCondition is truthy.
<Else>
This will only be shown if both someCondition and
otherCondition are both falsey.
</Else>
</ElseIf>
<Else>
This will be shown if someCondition is falsey.
<If case={finalCondition}>
This will be shown if someCondition is falsey
and finalCondition is truthy.
</If>
</Else>
</If>
Alternatively, you can provide then
and else
props.
<If case={someCondition} then={
"This will only be shown if someCondition is truthy."
} else={
"This will be shown if someCondition is falsey."
}/>
Only the newest, coolest, most blazing fast React architecture out there!
React Hooks has been an exciting development in the evolution of React, but it felt like it was only half of the story. React Loops completes the gripping picture by providing React's missing control-flow operators via JSX elements.