ReactJs Rating Stars Component / Example / Demo / Sourcecode Download

In this post I am going to share an awesome mini reactjs script to add rating star feature on your website. This is tiny reactjs code to implement rating star feature with your website product and services so that visitor can rate your product and services.
Reactjs Rating Stars Component

Libraries

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.1/react-dom.min.js"></script>

HTML

<div id="container"></div>


CSS

 .star {
  font-size: 2em;
  color: #ff851b;
  cursor: pointer;
}


JS

const Rating = React.createClass({ displayName: "Rating",
  getInitialState: function () {
    const stars = this.props.stars;
 
    return {
      value: stars,
      dynamicValue: stars };
 
  },
 
  handleClick: function (newValue) {
    this.setState({
      value: newValue,
      dynamicValue: newValue });
 
 
    if (this.props.onRated) {
      this.props.onRated(newValue);
    }
  },
 
  handleMouseEnter: function (newValue) {
    this.setState({ dynamicValue: newValue });
  },
 
  handleMouseLeave: function (newValue) {
    this.setState({ dynamicValue: this.state.value });
  },
 
  render: function () {
    const starSpans = [];
 
    for (let v = 1; v <= 5; v++) {if (window.CP.shouldStopExecution(0)) break;
      if (v <= this.state.dynamicValue) {
        starSpans.push( 
        React.createElement("span", {
          key: v,
          className: "star",
          onMouseEnter: this.handleMouseEnter.bind(this, v),
          onMouseLeave: this.handleMouseLeave.bind(this, v),
          onClick: this.handleClick.bind(this, v) }, "\u2605"));
 
 
 
 
      } else {
        starSpans.push( 
        React.createElement("span", {
          key: v,
          className: "star",
          onMouseEnter: this.handleMouseEnter.bind(this, v),
          onMouseLeave: this.handleMouseLeave.bind(this, v),
          onClick: this.handleClick.bind(this, v) }, "\u2606"));
 
 
 
 
      }
    }window.CP.exitedLoop(0);
 
    return React.createElement("div", null, starSpans);
  } });
 
 
function handleRated(newRating) {
  console.log(`The new rating is: ${newRating}`);
}
 
ReactDOM.render( 
React.createElement("div", null, 
React.createElement(Rating, { stars: 1, onRated: handleRated }), 
React.createElement(Rating, { stars: 2 }), 
React.createElement(Rating, { stars: 3 }), 
React.createElement(Rating, { stars: 4 }), 
React.createElement(Rating, { stars: 5 })),
 
document.getElementById('container'));

See live demo and download source code.
|

Don’t forget to Subscribe My Public Notebook for more useful free scripts, tutorials and articles.

This awesome script developed by dwayne. Visit their official repository for more information and follow for future updates.