Most reviews on the web have some sort of five-point rating... with stars being the most prevalent symbol. Five stars is great and one star is awful. The stars light up as you mouse over them to give an idea of what would happen if you clicked that star.
It’s super easy to do in React and I’m going to show you how. And... since React hooks have just been released officially, I'm going to show you using hooks inside functional components instead of state in class components.
Our control will have a fixed number of stars. You could do more or less than five but that’s the standard. Conceptually, from left to right the stars are numbered one through five and correspond to a rating from one to five.
When the cursor is over star N, light up stars 1 to N; and when the cursor is not over a star, the control should show the current rating, which may be null or 1 - 5.
We’ll use SVG for our stars so they’re scalable across different resolutions.
We’ll create one component for the star itself. It will take a prop that says whether it’s full or empty. Then we’ll create a "container" component that manages the rating.
And, as I mentioned earlier, we're going to use the React hooks to manage state.
Watch the video or download the project files
You may have noticed that we didn't write any unit tests this time.
The only real logic in this component is the one-line condition that determines whether a star is full or empty. That logic isn't going to be changing or used in different ways by future code. Better to spend our time elsewhere.
There you have it, Star Rating. Really simple, right?
The full source code and solution for the exercise are available for download exclusively by mailing list members. Also as a list member you'll get articles about modern web development topics like React, Redux, TypeScript, etc. emailed to you occasionally.