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

MySQL joint table query basic operation left-join common pitfalls

Overview For small and medium-sized projects, joi...

Detailed explanation of this pointing problem in JavaScript

Preface The this pointer in JS has always been a ...

Implementing simple tabs with js

Tab selection cards are used very frequently on r...

In-depth understanding of React Native custom routing management

Table of contents 1. Custom routing 2. Tab naviga...

Troubleshooting the reasons why MySQL deleted records do not take effect

A record of an online MySQL transaction problem L...

How does Vue download non-same-origin files based on URL

Generally speaking, we can have the following two...

JavaScript gets the scroll bar position and slides the page to the anchor point

Preface This article records a problem I encounte...

How to use VirtualBox to simulate a Linux cluster

1. Set up HOST on the host Macbook The previous d...

How to check the version of Kali Linux system

1. Check the kali linux system version Command: c...

Introduction to Enterprise Production MySQL Optimization

Compared with other large databases such as Oracl...

Implementation of CSS text shadow gradually blurring effect

text-shadow Add a shadow to the text. You can add...

Problem record of using vue+echarts chart

Preface echarts is my most commonly used charting...