Ben Ilegbodu ๐Ÿ€๐Ÿ‘จ๐Ÿพโ€๐Ÿ’ป Profile picture
#Christ follower, husband, father of 3๏ธโƒฃ. Tweetin' on #React #TypeScript #DivOps @NBA. ๐ŸŒ Speaker @GoogleDevExpert @MVPAward. Principal FE Eng @stitchfix

May 19, 2021, 7 tweets

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.

Keep scrolling