← All Articles A Product of Kinsa Creative

Use Array.from() to Generate a Sequence in JavaScript

mdn web docs contains an example for generating a sequence in JavaScript.

The example below uses it to create a star rating component where an array up to a max rating is generated and then iterated upon by using an arrow function as the map function for manipulating the elements in the array. A solid star is rendered if the iteration is less than the rating; otherwise, an empty star is rendered.

import StarOutline from "@/components/icons/star-outline.svg";
import StarSolid from "@/components/icons/star-solid.svg";

interface StarRatingProps {
    rating: number;
    maxStars?: number;
}

const StarRating = ({ rating, maxStars = 5 }: StarRatingProps) => {
    return (
        <div className="flex" aria-hidden="true">
            {Array.from({ length: maxStars }, (_, index) =>
                index < rating ? (
                    <StarSolid key={index} />
                ) : (
                    <StarOutline key={index} />
                ),
            )}
        </div>
        <span className="sr-only">Rating: {rating} out of {maxStars} stars.</span>
    );
};

Use: <StarRating rating={3} />

Feedback?

Email us at enquiries@kinsa.cc.