This solution is generated by ChatGPT, correctness is not guaranteed.

AI solution for System Design on BFE.dev
8. Create a Star Widget

To create the star widget, we can use HTML, CSS and JavaScript. Here's how:

  1. HTML: We can create the star widget using HTML and CSS by creating a container div with a class name “star-widget”. Inside this container, we can create five span elements representing the five stars. Each span element will have a unique ID (star1, star2, star3, star4, star5) and a class name “star”.
<div class="star-widget">
  <span id="star1" class="star"></span>
  <span id="star2" class="star"></span>
  <span id="star3" class="star"></span>
  <span id="star4" class="star"></span>
  <span id="star5" class="star"></span>
</div>
  1. CSS: We can then use CSS to style the stars by using the :before and :after pseudo elements to create half stars when required.
.star-widget{
  font-size: 0;
  display: flex;
  justify-content: center;
}
.star{
  position: relative;
  display: inline-block;
  font-size: 20px;
  color: gray;
  transition: color .2s;
  cursor: pointer;
}
.star:before,
.star:after{
  content:'★';
  position: absolute;
  left: 0;
  color: #ffa726;
}
.star:before{
  opacity: 0;
  transition: opacity .2s;
}
.star:hover:before,
.star:hover ~ .star:before{
  opacity: 1;
}
.star:nth-child(1):before{
  opacity: 1;
}
.star:nth-child(2):before,
.star:nth-child(2):hover:before,
.star:nth-child(2):hover ~ .star:before{
  opacity: 1;
}
  1. JavaScript: Finally, we can use JavaScript to make the stars interactive by adding click event listeners to each star. When a star is clicked, we can change its color and the colors of the stars before it to yellow. We can also store the value of the selected star(s) in a hidden input field for easy submission in a form.
const stars = document.querySelectorAll('.star');
const rating = document.querySelector('.rating');
const sendBtn = document.querySelector('#send');
let index;

stars.forEach((star, i) => {
  star.addEventListener('click', function(){
    index = i;
    rating.value = index + 1;
    stars.forEach((s, j) => {
      if(j <= index){
        s.classList.add('rated');
      }else{
        s.classList.remove('rated');
      }
    });
  });
});

sendBtn.addEventListener('click', function(){
  alert(`You rated: ${rating.value}`);
});

To make the star widget reusable, we can create a separate file for the HTML, CSS and JavaScript code and link it to any page where the widget is needed.

To make it also work as a common input field in a form, we can add a hidden input field with a class name “rating” inside the container div.

<input type="hidden" name="rating" class="rating">

We can then submit the value of the rating input field along with other form fields.