In many blog post, I use .map
to iterate over an array of data to render one React element per item. But what if we don't have an array?
Think about those star ratings you see everywhere - you know, the ones that go from zero to five stars? Well, let's say we want to show these little star icons based on whatever rating we get.
This is a tricky problem!
Our default tool in JavaScript to do this sort of thing would be a for
loop. As we've learned, though, for
is a statement, and we can't use statements within our JSX.
Here's one solution: we can use a for
loop above the JSX, to create our array of elements:
function StarRating({ rating }) {
let stars = [];
for (let i = 0; i < rating; i++) {
stars.push(
<img
key={i}
alt=""
className="gold-star"
src="<https://random/img/gold-star.svg>"
/>
);
}
return (
<div className="star-wrapper">
{stars}
</div>
);
}
We create an array of image elements with a for
loop, and then we render that array inside our JSX. As we saw with .map
, React can βunpackβ arrays for us, and render each of the elements inside, so long as we provide a unique key
for each element.
A functional alternative
Hey, this way works fine, but I want to show you something cooler - we can use what's called a range
function instead.
Think of range
it as a helpful tool that makes our job easier. While it's not built into JavaScript (unfortunately), you can find it in handy packages like lodash.
I absolutely love this little helper!
It's so useful that I end up using it in literally every project I work on. No joke - I've used it more than 20 times just building this course platform!
Let me show you how easy it is to use with some examples:
// Create an array from 0 (inclusive) to 2 (exclusive):
range(2);
// Produces: [0, 1]
// Create an array from 0 (inclusive) to 5 (exclusive):
range(5);
// Produces: [0, 1, 2, 3, 4]
// Create an array from 2 (inclusive) to 6 (exclusive):
range(2, 6);
// Produces: [2, 3, 4, 5]
// Create an array from 2 to 10, picking every 2nd number
range(2, 10, 2);
// Produces: [2, 4, 6, 8]
Essentially, it's the expression version of a βforβ loop statement, like how &&
can be an expression version of an βifβ statement. This means we can use it in our JSX.
Here's how we'd use it:
function StarRating({ rating }) {
return (
<div className="star-wrapper">
{range(rating).map((num) => (
<img
key={num}
alt=""
className="gold-star"
src="<https://random/img/gold-star.svg>"
/>
))}
</div>
);
}
range(rating)
creates an array starting from 0 and going up to (but not including) n
, where n
is the supplied rating. We then use the .map
trick to loop through that array, creating a star image for each number.
We use each number from the array as the key
prop, since these numbers are guaranteed to be unique.
For a rating of 4, we will have something like this:
Range function code
Here's how the range
function is defined:
const range = (start, end, step = 1) => {
let output = [];
if (typeof end === 'undefined') {
end = start;
start = 0;
}
for (let i = start; i < end; i += step) {
output.push(i);
}
return output;
};
The solution code demonstrating this function, will look like this:
function StarRating({ rating }) {
return (
<div className="star-wrapper">
{range(rating).map((num) => (
<img
key={num}
alt=""
className="gold-star"
src="<https://random/img/gold-star.svg>"
/>
))}
</div>
);
}
const range = (start, end, step = 1) => {
let output = [];
if (typeof end === 'undefined') {
end = start;
start = 0;
}
for (let i = start; i < end; i += step) {
output.push(i);
}
return output;
};
export default StarRating;
<section>
<h2>The Galaxy, And The Ground Within</h2>
<p>
Rating: 5 / 5
</p>
<StarRating rating={5} />
</section>
In terms of using this in the real world, I like to create a utils.js
file that collects this and other handy JS functions.
We can solve this problem using modern built-in array methods. There are a few ways to do this, but here's the most straightforward option I've seen:
{Array(rating).fill().map((_, index) => (
β...
))}
I'll be honest - I don't really like this way of doing things. It's kind of like looking under the hood of your car - there's a lot of complicated stuff going on that we don't need to see.
Plus, it's pretty limited - you can't choose where to start counting from or how big the steps should be. I prefer to keep things simple with a helper function that I can use whenever I need to create a list of numbers. I've been using this trusty old
range
function in many projects, and it's never let me down! πEnd
We've shown you how the range utility makes React coding much easier when you need to work with numbers. Instead of using old-school for loops or messy array tricks, range gives you a simple way to create number sequences right in your JSX code.
So whether you're making something cool like star ratings or just working with numbers, think of range as your new coding buddy. It's a simple tool that'll help you write better, easier-to-read React code!
π. Similar posts
How to Handle Asynchronous Updates with useState in Your React App
30 Jan 2025
How to Effectively Use Event Handlers in React with Arguments
28 Jan 2025
Everything You Need to Know About React Conditional Logic
22 Jan 2025