Implementation of React star rating component

Implementation of React star rating component

The requirement is to pass in the rating data for the product, and the page will display the corresponding number of stars.

1. Prepare three star pictures corresponding to different ratings

insert image description here
insert image description hereinsert image description here

2. Expected results

Such

insert image description here

Call

<StarScore score={data.wm_poi_score}/>

3. Process the incoming data

We need to get the integer and decimal parts of the score

let wm_poi_score = this.props.score || '';
let score = wm_poi_score.toString();
let scoreArray = score.split('.');

If 4.7 is passed in, the resulting scoreArray is ['4', '7']

4. Calculate the corresponding number of stars based on the data

// Full star number let fullstar = parseInt(scoreArray[0]);
// Number of half stars let halfstar = parseInt(scoreArray[1]) >= 5 ? 1 : 0;
// Number of gray stars let nullstar = 5 - fullstar - halfstar;

5. Render components according to the number of stars

let starjsx = [];
// Render full stars for (let i = 0; i < fullstar; i++) {
  starjsx.push(<div key={i + 'full'} className="star fullstar"></div>)
}
// Render half star if (halfstar) {
  for (let j = 0; j < halfstar; j++) {
    starjsx.push(<div key={j + 'half'} className="star halfstar"></div>)
  }
}
// Render gray star if (nullstar) {
  for (let k = 0; k < nullstar; k++) {
    starjsx.push(<div key={k + 'null'} className="star nullstar"></div>)
  }
}

OK, the effect we want is achieved.

6. Manual Scoring

insert image description here

When the page is first displayed, 5 gray stars are rendered. Add a click event to each star. When clicked, get the subscript index corresponding to the star and add a highlight style to it.

<div className="star-area">
  {this.renderStar()}
</div>
doEva(i) {
  this.setState({
    startIndex: i + 1
  });
}

renderStar() {
  let array = []
  for (let i = 0; i < 5; i++) {
    let cls = i >= this.state.startIndex ? "star-item" : "star-item light"
    array.push(
      <div onClick={() => this.doEva(i)} key={i} className={cls}></div>
    )
  }
  return array
}

Complete code

import React from 'react';
import './StarScore.scss';

// Render 5 star score method class StarScore extends React.Component {
  renderScore() {
    let wm_poi_score = this.props.score || '';
    let score = wm_poi_score.toString();
    let scoreArray = score.split('.');
    // Full star number let fullstar = parseInt(scoreArray[0]);
    // Number of half stars let halfstar = parseInt(scoreArray[1]) >= 5 ? 1 : 0;
    // Number of gray stars let nullstar = 5 - fullstar - halfstar;
    let starjsx = [];

    // Render full stars for (let i = 0; i < fullstar; i++) {
      starjsx.push(<div key={i + 'full'} className="star fullstar"></div>)
    }
    // Render half star if (halfstar) {
      for (let j = 0; j < halfstar; j++) {
        starjsx.push(<div key={j + 'half'} className="star halfstar"></div>)
      }
    }
    // Render gray star if (nullstar) {
      for (let k = 0; k < nullstar; k++) {
        starjsx.push(<div key={k + 'null'} className="star nullstar"></div>)
      }
    }
    return starjsx;
  }
  render() {
    return <div className="star-score">{this.renderScore()}</div>;
  }
}

export default StarScore;

StarScore.scss

.star-score {
  .star {
    width: 10px;
    height: 10px;
    float: left;
    background-size: cover;
  }

  .fullstar {
    background-image: url('./img/fullstar.png');
  }

  .halfstar {
    background-image: url('./img/halfstar.png');
  }

  .nullstar {
    background-image: url('./img/gray-star.png');
  }
}
import './Main.scss';
import React from 'react';

class Main extends React.Component {
  constructor(props) {
    super(props);
    }
  }
  
  /**
   * Click to rate */
  doEva(i) {
    this.setState({
      startIndex: i + 1
    });
  }
  /**
   * Stars for rendering rating */
  renderStar() {
    let array = []
    for (let i = 0; i < 5; i++) {
      let cls = i >= this.state.startIndex ? "star-item" : "star-item light"
      array.push(
        <div onClick={() => this.doEva(i)} key={i} className={cls}></div>
      )
    }
    return array
  }
  render() {
    return (
      <div className="content">
        <div className="star-area">
            {this.renderStar()}
          </div>
      </div>
    );
  }
}

export default Main;
.content {
  height: 100%;
  .eva-content {
    background-color: #fff;
    overflow: hidden;
    margin: px2rem(10px);
    margin-top: px2rem(74px);
  }
  .star-area {
    text-align: center;
    margin-top: px2rem(30px);
  }
  .star-item {
    width: px2rem(32px);
    height: px2rem(32px);
    background-image: url('./img/gray-star.png');
    background-size: cover;
    display: inline-block;
    margin-right: px2rem(10px);

    &.light {
      background-image: url('./img/light-star.png');
    }
  }
}

This is the end of this article about the implementation of the React star rating component. For more relevant React star rating content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • React uses antd's upload component to implement the file form submission function (complete code)
  • Solution to React pure function component setState not refreshing the page update
  • React implements dynamic pop-up window component
  • How to make React components full screen

<<:  Detailed explanation of how to use CMD command to operate MySql database

>>:  MySQL query duplicate data (delete duplicate data and keep the one with the smallest id as the only data)

Recommend

Implementation of socket options in Linux network programming

Socket option function Function: Methods used to ...

Pure CSS to achieve click to expand and read the full text function

Note When developing an article display list inte...

MySQL date functions and date conversion and formatting functions

MySQL is a free relational database with a huge u...

Linux kernel device driver system call notes

/**************************** * System call******...

Html tips to make your code semantic

Html semantics seems to be a commonplace issue. G...

Calendar effect based on jQuery

This article example shares the specific code of ...

Summary of MySQL common SQL statements including complex SQL queries

1. Complex SQL queries 1.1. Single table query (1...

Problems installing TensorRT in docker container

Uninstall the installed version on Ubuntu: sudo a...

Detailed installation process of MySQL5.6.40 under CentOS7 64

MySQL5.6.40 installation process under CentOS7 64...

Which loop is the fastest in JavaScript?

Knowing which for loop or iterator is right for o...

Detailed tutorial on compiling and installing python3.6 on linux

1. First go to the official website https://www.p...

Achieve 3D flip effect with pure CSS3 in a few simple steps

As a required course for front-end developers, CS...

Why MySQL chooses Repeatable Read as the default isolation level

Table of contents Oracle Isolation Levels MySQL I...