Nope JSX doesn't have a built-in loop construct. Instead it offloads looping to JavaScript & just accepts an array of JSX elements for rendering lists
๐ก So in React, to loop we gotta convert an array of data โก๏ธ array of JSX elements
Let's look at some ways how...
/thread ๐งต๐๐พ
Calling `.map` on the array is the most popular way to generate that array of JSX elements
And cuz `.map` returns a new array we can inline it directly in the JSX w/o using a var (also very common)
Putting the `.map` inline makes it *feel* like traditional loop templates
๐งต๐๐พ
Using a regular `for` loop (or `for-of`, `.forEach`, etc) requires a var that we gotta `.push` into
`for` is likely more familiar to JS newcomers but it means we cannot inline the code
...unless we wanna go rogue and put it in an IIFE ๐คฏ (anyone used one here before???)
๐งต๐๐พ
Buuut if you really want looping in your JSX, babel-plugin-jsx-control-statements adds a JSX element to enable it
There's nothing to import in the source code. Just use the `<For>` element
github.com/AlexGilleran/jโฆ
This was a common approach in React's early days
๐งต๐๐พ
Lastly, what if our data source isn't an array (or object)? Like a number or something? We can use a `for` loop directly
But since I prefer functional-style programming I first convert that number into an array, then use good ol' `.map`
๐งต๐๐พ
If you're new to React, hopefully this info can clarify looping for you
Or if you already know React, it'll provide examples of how to explain it to those teammates you're training ๐๐พ
You can also share this post w/ the full details
๐งต๐๐พ
benmvp.com/blog/looping-iโฆ
I've got a weekly newsletter where I share this type of content. It's not the link aggregator type, but it contains a brand new post & an old one I share
It's all about the frontend: JS/TS, React, DivOps, CSS & more! Subscribe to get your learn on ๐
benmvp.com/subscribe/?utmโฆ
Share this Scrolly Tale with your friends.
A Scrolly Tale is a new way to read Twitter threads with a more visually immersive experience.
Discover more beautiful Scrolly Tales like this.