If you are looking for a ranking star function to add to your website, then you are at the right place. Today, I am going to share a mini reactjs script to add a ranking star function to post and pages. This is a very small reactjs code to implement the star rating feature with your website’s products and services so that visitors can rate your products and services.
Libraries
Add these libraries in the header section of your website.
<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
Add this html line in your webpage where you want to show rating.
<div id="container"></div>
CSS
Add this CSS code in your website.
.star {
font-size: 2em;
color: #ff851b;
cursor: pointer;
}
JS
This is the main JavaScript. add this in your webpage.
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( /*#__PURE__*/
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( /*#__PURE__*/
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 /*#__PURE__*/React.createElement("div", null, starSpans);
} });
function handleRated(newRating) {
console.log(`The new rating is: ${newRating}`);
}
ReactDOM.render( /*#__PURE__*/
React.createElement("div", null, /*#__PURE__*/
React.createElement(Rating, { stars: 1, onRated: handleRated }), /*#__PURE__*/
React.createElement(Rating, { stars: 2 }), /*#__PURE__*/
React.createElement(Rating, { stars: 3 }), /*#__PURE__*/
React.createElement(Rating, { stars: 4 }), /*#__PURE__*/
React.createElement(Rating, { stars: 5 })),
document.getElementById('container'));
You can also download the all files in ZIP format.
This awesome script developed by dwayne. Visit their official repository for more information and follow for future updates.