React Rating - JavaScript Exercise #12

React Rating - JavaScript Exercise #12

Build a React Rating Component

ยท

4 min read

Overview

In this exercise, you will create a React component that allows users to rate a product on a scale of 1 to 5. The rating will be displayed as a set of stars, with each star representing one point.

Requirements

  • The component should accept a prop for the initial rating value.

  • The component should allow the user to update the rating by clicking on the stars.

  • The component should display the rating as a set of stars, with a filled star representing a point and an empty star representing no point.

  • The component should provide a callback function that returns the updated rating value to the parent component.

Instructions

  1. Create a new React component called Rating using the class syntax.

  2. Define a state property called "rating" and initialize it with the initial rating value passed in as a prop.

  3. In the render method, create a set of five-star icons.

  4. Add an handleClick event listener to each star icon that updates the "rating" state property to the corresponding value.

  5. Use conditional rendering to fill in the stars up to the current rating value.

  6. Add a callback function prop called onRatingChange which accepts the updated rating value as an argument and passes it back to the parent component.

  7. Call the onRatingChange function every time the rating is updated.

Bonus Requirements

  • Add hover effects to the star icons to highlight the stars when the user hovers over them.

  • Add the ability to display a text label next to the rating to indicate the number of stars selected.

  • Customize the appearance of the stars based on the rating value. For example, you could change the color of the stars to yellow for a high rating and red for a low rating.

Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.

So, grab a pen and paper, fire up your code editor, and get ready to dive into the React Rating exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.

Output for the Rating exercise

import React, { useState } from 'react';
import './Rating.css';

const Rating = ({ onRatingChange }) => {
  const [rating, setRating] = useState(null);

  const handleClick = (event) => {
    const newRating = event.target.value === rating ? null : event.target.value;
    setRating(newRating);
    onRatingChange(newRating);
  };

  return (
    <div className="rating">
      {[1, 2, 3, 4, 5].map((value) => (
        <React.Fragment key={value}>
          <input
            type="checkbox"
            name="rating"
            id={`rating-${value}`}
            value={value}
            checked={value <= rating}
            onChange={handleClick}
          />
          <label htmlFor={`rating-${value}`}></label>
        </React.Fragment>
      ))}
    </div>
  );
};

export default Rating;
.rating {
  display: flex;
  align-items: center;
  font-size: 0;
}

.rating input {
  display: none;
}

.rating label {
  display: inline-block;
  width: 20px;
  height: 20px;
  margin-right: 5px;
  cursor: pointer;
  position: relative;
}

.rating label::before {
  content: "\2605";
  position: absolute;
  left: 0;
  top: 0;
  font-size: 20px;
  color: #ccc;
}

.rating input:checked + label::before,
.rating label:hover:before {
  color: #ff9800;
}
import React, { useState } from 'react';
import Rating from './Rating';

const App = () => {
  const [rating, setRating] = useState(null);

  const handleRatingChange = (newRating) => {
    setRating(newRating);
  };

  return (
    <div>
      <h1>Rate this product:</h1>
      <Rating onRatingChange={handleRatingChange} />
      {rating && <p>You rated this product {rating} stars!</p>}
    </div>
  );
};

export default App;

The Rating component can be used in a variety of applications where you need to collect user feedback or ratings. Here are a few examples:

  1. Product rating: Allow users to rate products on your e-commerce site or app.

  2. Restaurant rating: Allow users to rate restaurants and their dishes.

  3. Movie rating: Allow users to rate movies and provide feedback.

  4. Feedback form: Use the Rating component as part of a larger feedback form, allowing users to rate different aspects of your product or service.

  5. Online learning platform: Use the Rating component to allow students to rate courses or individual lessons.

  6. Employee performance review: Use the Rating component to allow managers to rate their employees' performance.

  7. Travel review: Allow users to rate hotels, flights, or tourist attractions.

  8. Event review: Allow users to rate events they've attended, such as concerts or conferences.

These are just a few examples of how you could use the Rating component, but the possibilities are endless!

I hope this exercise and code examples were helpful to you! The Rating component can be a useful addition to many different types of applications, allowing you to collect valuable feedback and ratings from your users.

Thanks for taking this JavaScript exercise!

I hope you found this exercise helpful and enjoyable, and that it has deepened your understanding of React development. Keep practising and experimenting with React, and you'll be well on your way to becoming a skilled React developer!

If you have any questions or comments, feel free to reach out to me on Twitter(@rajeshtomjoe), or follow me for more updates.

And if you'd like to receive more exercise on JavaScript, be sure to subscribe to my blog.

ย