A simple star rating component for your React projects

Last update: Apr 16, 2022

react-stars

A simple star rating component for your React projects (now with half stars and custom characters)

react-stars

Get started quickly

Install react-stars package with NPM:

npm install react-stars --save

Then in your project include the component:

import ReactStars from 'react-stars'
import React from 'react'
import { render } from 'react-dom'

const ratingChanged = (newRating) => {
  console.log(newRating)
}

render(<ReactStars
  count={5}
  onChange={ratingChanged}
  size={24}
  color2={'#ffd700'} />,

  document.getElementById('where-to-render')
);

API

This a list of props that you can pass down to the component:

Property Description Default value type
className Name of parent class null string
count How many total stars you want 5 number
value Set rating value 0 number
char Which character you want to use as a star string
color1 Color of inactive star (this supports any CSS valid value) gray string
color2 Color of selected or active star #ffd700 string
size Size of stars (in px) 15px string
edit Should you be able to select rating or just see rating (for reusability) true boolean
half Should component use half stars, if not the decimal part will be dropped otherwise normal algebra rools will apply to round to half stars true boolean
onChange(new_rating) Will be invoked any time the rating is changed null function

Help improve the component

Build on your machine:
# Clone the repo
git clone [email protected]:n49/react-stars.git
# Go into project folder
cd react-stars
# Install dependancies
npm install

Build the component:

npm build

Run the examples (dev):

npm run dev-example

Build the examples (production):

npm run build-example

Then in your browser go to: http://127.0.0.1:8080/example

Requirements

You will need to have React in your project in order to use the component, I didn't bundle React in the build, because it seemed like a crazy idea.

Todo

  • Make better docs
  • Better state management
  • Write tests

GitHub

https://github.com/n49/react-stars
Comments
  • 1. if edit is set to false, set pointer to default

    Hey thanks for creating an awesome library!

    I'd like to propose a change:

    • If edit is true, set the cursor to pointer
    • Else set the cursor to default

    Thanks!

    Reviewed by peterpme at 2017-01-09 18:01
  • 2. User cannot change stars when edit property is passed as true

    How to setup test:

    1. Follow instructions provided in readme.
    2. Change one of the component configurations in /example/index.js to include edit: true E.g.
    const secondExample = {
      size: 50,
      count: 10,
      char: '',
      edit: true, // Added this property
      color1: '#ff9900',
      color2: '#6599ff',
      onChange: newValue => {
        console.log(`Example 2: new value is ${newValue}`)
      }
    }
    
    1. Run npm run dev-example and observe how the apple rater does not work anymore
    Reviewed by anvk at 2017-11-03 19:09
  • 3. Half stars not appearing, even with value={4.5} and half={true}

    Hi! Thanks for the nice component. I have one issue with it though, I can't get the half stars to show.

    Half stars not appearing, even with value={4.5} and half={true}

    Any ideas why ?

    Reviewed by FredGauld at 2017-05-30 14:25
  • 4. Added value to the documentation

    There may be a case where one should want to use this widget to display a read-only value. In this case one should set edit to false and value (which can be set as a state from the parent) to the preferred value.

    Reviewed by GabMus at 2017-05-23 11:14
  • 5. have propTypes

    like

    ReactStars.propTypes = {
        count: PropTypes.optionalNumber,
        onChange: PropTypes.optionalFunc,
        half: PropTypes.optionalBool
    //  ...otherProps 
    }
    
    Reviewed by Hermanya at 2016-04-14 20:23
  • 6. hover and default cursor

    New functions were created(copied and modified) for onMouseOver event and onMouseLeave event. I also copied the style for cursor, so the default cursor is used if edit is false. I realise that copying the code is not a good solution, but I am not prepared to put any more time into this component. I customised it so it works for my case and I think the changes can benefit other developers.

    Reviewed by bostjan242 at 2017-06-21 07:07
  • 7. The component ReactStars won't let me use setState({})

    We found an issue on the ReactStars component when trying to set a state.

    Here is the code to reproduce the problem:

    import React from 'react';
    import Relay from 'react-relay';
    import autobind from 'autobind-decorator';
    import ReactStars from 'react-stars';
    
    export default class BookPagePostReview extends React.Component {
      constructor(props) {
        super(props);
        this.state = {
          rating: 0,
        };
      }
    
      @autobind
      onStarClick(value) {
        this.setState({rating: value});
      }
    
      render() {
        return (
        <div>
          <ReactStars
            count={5}
            size={24}
            onChange={this.onStarClick}
           />
        </div>
        );  
      }
    }
    

    Problem: When clicking the stars the new state is set, but the stars won't show the rating I picked (i.e. if I click 3 stars, it will show nothing). That in terms of User Experience is not the optimal result.

    The solution we found for this problem is using:

      @autobind
      onStarClick(value) {
        this.state.rating = value;
      }
    

    But that one is not ideal for React.

    Reviewed by seque1990 at 2016-06-23 02:22
  • 8. Hello guys I'm having an issue to keep the format!

    Hello and first of all thanks, it's a nice feature.

    I'm having this issue:

    When I select and number of stars the format do not change at the first click (generally), I need to press several times. And the principal issue is that after rate when I begin typing at next input the format disappear. It doesn't behave like the secondExample : Thanks in advance!

    const secondExample = {
      size: 50,
      count: 10,
      char: '',
      color1: '#ff9900',
      color2: '#6599ff',
      onChange: newValue => {
        console.log(`Example 2: new value is ${newValue}`)
      }
    }
    

    This is my code:

    function EditReview({editReview, user, product}) {
      const[show, setShow] = useState(false);
      const [stars, setStars] = useState(0);
      const [description, setDescription] = useState('');
    
      const handleOnclick = (e) => {
        e.preventDefault();
        setShow(true);
      }
      const handleOnChange = (e) => {
        e.preventDefault();
        setDescription(e.target.value)
        console.log(e.target.value)
      }
      
      const handleOnSubmit = (e) => {
        e.preventDefault();
        const review = {
          description: description,
          qualification: Math.round(stars),
          userdId: user.id
        };
        const id = product.id
        editReview(id, review);
        setShow(false);
      }
      const star = {
        count:5,
        onChange: stars=>setStars(stars),
        size: 74,
        color2: '#8a2be2',
        half: false,
      }
      return (
        <React.Fragment>
          <Button 
            onClick={(e)=>handleOnclick(e)}
            className=""
          >Edit review
          </Button>
          <Modal 
            show={show} 
            onHide={()=>setShow(false)}
            keyboard={true}
            animation={true}
            centered={true}
          >
            <Modal.Header
              closeButton={true} 
              closeLabel={'Close'}
            >
              <Modal.Title>Change your review</Modal.Title>
            </Modal.Header>
            <Modal.Body>
              <h4>Rate the product.</h4>
              <Form>
                <ReactStars {...star}/>
                <hr/>
                <h4>The new product review?</h4>
                <InputGroup>
                  <InputGroup.Prepend>
                    <InputGroup.Text>Your review</InputGroup.Text>
                  </InputGroup.Prepend>
                  <FormControl 
                    as="textarea"  
                    aria-label="Description" 
                    placeholder="I hope it's for better"
                    onChange={e=>handleOnChange(e)}
                  />
                </InputGroup>
              </Form>
            </Modal.Body>
    //                  ...
    
    Reviewed by larts85 at 2020-10-23 17:17
  • 9. Problem with half star classes

    Hi, I'm using a select component with react-stars and when I choose a rating with a half star, just the half star render overlapping the options of the select, but it only happens with the half stars because it has z-index 1, but I don't know how to change it to 0, does somebody have the same problem?

    Reviewed by Sleepwalker18 at 2020-06-26 17:33
  • 10. Rest state of stars when i change the parent state

    Hello, When i try to update the state of parent component, the state change correctly but the stars don't stay selected

    onChange: newValue => { console.log(Example 3: new value is ${newValue}) thiz.props.parentAction(newValue); }

    Reviewed by KLadnany at 2018-02-09 14:30
  • 11. Improved docs by Adding Documentation Based on Example Code

    1. added documentation based on example code

    2. fixed tiny bug in example: "npm build" was changed to "npm run build". It was not working on my system(I think NPM updated) so I have changed it to "npm run build". Using this change, It can work universally.

    Let me know if there are any issues and what I can do to fix them. Thanks!

    Reviewed by akashshyamdev at 2021-05-27 13:19
  • 12. Hello guys, It is not keeping the format :(

    Hello and first of all thanks, it's a nice feature.

    I'm having this issue:

    When I select and number of stars the format do not change at the first click (generally), I need to press several times. And the principal issue is that after rate when I begin typing at next input the format disappear. It doesn't behave like the secondExample : Thanks in advance!

    const secondExample = {
      size: 50,
      count: 10,
      char: '',
      color1: '#ff9900',
      color2: '#6599ff',
      onChange: newValue => {
        console.log(`Example 2: new value is ${newValue}`)
      }
    }
    

    This is my code:

    function EditReview({editReview, user, product}) {
      const[show, setShow] = useState(false);
      const [stars, setStars] = useState(0);
      const [description, setDescription] = useState('');
    
      const handleOnclick = (e) => {
        e.preventDefault();
        setShow(true);
      }
      const handleOnChange = (e) => {
        e.preventDefault();
        setDescription(e.target.value)
        console.log(e.target.value)
      }
      
      const handleOnSubmit = (e) => {
        e.preventDefault();
        const review = {
          description: description,
          qualification: Math.round(stars),
          userdId: user.id
        };
        const id = product.id
        editReview(id, review);
        setShow(false);
      }
      const star = {
        count:5,
        onChange: stars=>setStars(stars),
        size: 74,
        color2: '#8a2be2',
        half: false,
      }
      return (
        <React.Fragment>
          <Button 
            onClick={(e)=>handleOnclick(e)}
            className=""
          >Edit review
          </Button>
          <Modal 
            show={show} 
            onHide={()=>setShow(false)}
            keyboard={true}
            animation={true}
            centered={true}
          >
            <Modal.Header
              closeButton={true} 
              closeLabel={'Close'}
            >
              <Modal.Title>Change your review</Modal.Title>
            </Modal.Header>
            <Modal.Body>
              <h4>Rate the product.</h4>
              <Form>
                <ReactStars {...star}/>
                <hr/>
                <h4>The new product review?</h4>
                <InputGroup>
                  <InputGroup.Prepend>
                    <InputGroup.Text>Your review</InputGroup.Text>
                  </InputGroup.Prepend>
                  <FormControl 
                    as="textarea"  
                    aria-label="Description" 
                    placeholder="I hope it's for better"
                    onChange={e=>handleOnChange(e)}
                  />
                </InputGroup>
              </Form>
            </Modal.Body>
    //                  ...
    
    Reviewed by larts85 at 2020-10-23 17:16
  • 13. Licensing

    Hey!

    I love the work that has been put in into this project. I cannot seem to find a licence for this - would you point me to it, or if its not available would you be able to license the project?

    Reviewed by zimnyjakub at 2020-09-03 14:59
  • 14. Warning: componentWillReceiveProps has been renamed

    react_devtools_backend.js:2273 Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-unsafe-component-lifecycles for details.

    • Move data fetching code or side effects to componentDidUpdate.
    • If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://fb.me/react-derived-state
    • Rename componentWillReceiveProps to UNSAFE_componentWillReceiveProps to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name will work. To rename all deprecated lifecycles to their new names, you can run npx react-codemod rename-unsafe-lifecycles in your project source folder.

    Please update the following components: ReactStars

    Reviewed by HauresBogdan at 2020-09-03 10:59
  • 15. After re-rendering, the star value is not changing to 0, its still set to the selected value.

    export const FeedbackPage = () => {

    const [ratedstars, setRatedstars] = useState(0);
    const [ratings, setRatings] = useState('');
    const [suggestions, setSuggestions] = useState('');
    
    const ratingChanged = (value) => setRatedstars(value);
    const onRatingschange = event => setRatings(event.target.value);
    const onSuggestionschange = event => setSuggestions(event.target.value);
    
    const clearForm = () => {
        setRatedstars(0);
        setRatings('');
        setSuggestions('');
        console.log(ratedstars,'ratedstars---------------------------------------')
    }
    
    const updateFeedback = () =>  {
        const web = Web("");
        web.lists.getByTitle('Feedback')
        .items.add({
            Pleaseexplainyourrating : {ratedstars},
            Doyouhaveanysuggestionsforimprov :  {ratings},
            How_x0020_useful_x0020_is_x0020_ : {suggestions}
          }).then(() => {
              alert('success');
          }).catch(() =>  {
              clearForm()
              alert('failure')
          });
    }
    
    
    return (
        <div className="main-divstyle">
        <div className="hdr-style">Feedback</div>
        <div className="ques-style required"> How useful is the company financials Dashboard? </div>
        <div className="rating-style">
        <ReactStars
        count={5}
        value={ratedstars}
        onChange={ratingChanged}
        size={50}
        isHalf={true}
        emptyIcon={<i className="far fa-star"></i>}
        halfIcon={<i className="fa fa-star-half-alt"></i>}
        fullIcon={<i className="fa fa-star"></i>}
        activeColor="#ffe600"
        a11y={true}
        />
    
        </div>
        <div className="ques-style required"> Please explain your rating.</div>
        <textarea className='textarea-style' value={ratings} onChange={onRatingschange}></textarea>
        <div className="ques-style">Do you have any suggestions for improvement? Please be specific.</div>
        <textarea className='textarea-style' value={suggestions}  onChange={onSuggestionschange}></textarea>
        <div><button className="btn-style" onClick={updateFeedback}>Submit</button></div>
        </div>
    );
    

    }

    Reviewed by manueldho at 2020-07-20 14:36
[Looking for Maintainers (email me)]: A simple star rating component built with React.
[Looking for Maintainers (email me)]: A simple star rating component built with React.

react-star-rating A simple star rating component built with React. Install $ npm install react-star-rating --save Include the css: <link rel="styleshe

Jan 17, 2022
The star rating
The star rating

React Awesome Stars Rating · React Awesome Stars Rating is a simple star component with easy integration for your React applications. Table of Content

Feb 5, 2022
A small and simple component to create icons from a rating
A small and simple component to create icons from a rating

A small and simple library that transform you rating in icons for you web

Nov 13, 2021
Star-wars-api - SWAPI project using React and TypeScript
Star-wars-api - SWAPI project using React and TypeScript

Small project using React and TypeScript to start the app use NPM start

Feb 1, 2022
React.js components for entering 0—N stars (N is 5 by default), or displaying 0—N stars

About React.js components for entering 0—N stars (N is 5 by default), or displaying 0—N stars. See the demo. It's published to npm compiled to ES5, an

Jul 10, 2021
A simple react component for adding a star rating to your project.
A simple react component for adding a star rating to your project.

A simple react component for adding a star rating to your project.

May 14, 2022
[Looking for Maintainers (email me)]: A simple star rating component built with React.
[Looking for Maintainers (email me)]: A simple star rating component built with React.

react-star-rating A simple star rating component built with React. Install $ npm install react-star-rating --save Include the css: <link rel="styleshe

Jan 17, 2022
A simple rating library for react native supporting: decimal points, direction aware icons, custom icon set from Ionicons, custom images and record rating given by users.
A simple rating library for react native supporting: decimal points, direction aware icons, custom icon set from Ionicons, custom images and record rating given by users.

React Native Rating Element A simple rating library for react native supporting: a11y ready ⚛️ decimal points like 3.7, 4.2 etc, direction aware icons

Feb 24, 2022
A Google Playstore like star rating chart as a React component.
A Google Playstore like star rating chart as a React component.

react-star-rating-chart A React component that is inspired by the Google Play Store start rating chart. under construction This component is not maint

Oct 8, 2021
The star rating
The star rating

React Awesome Stars Rating · React Awesome Stars Rating is a simple star component with easy integration for your React applications. Table of Content

Feb 5, 2022
Star-Wars-Memory-Game - Star Wars Memory Game Using React.js
Star-Wars-Memory-Game - Star Wars Memory Game Using React.js

Star-Wars-Memory-Game Um jogo da memória com tematica do Star Wars. O objetivo e

Feb 25, 2022
A small and simple component to create icons from a rating
A small and simple component to create icons from a rating

A small and simple library that transform you rating in icons for you web

Nov 13, 2021
A small and simple component to create icons from a rating
A small and simple component to create icons from a rating

Pretty rating React A small and simple library that transform you rating in icons for you web Status Getting started To install as npm dependency npm

Nov 13, 2021
A React Native component for generating and displaying interactive star ratings
A React Native component for generating and displaying interactive star ratings

React Native Star Rating Component A React Native component for generating and displaying interactive star ratings. Compatible with both iOS and Andro

May 12, 2022
A tiny library to support Huawei AppGallery in-app rating/commenting for React-Native
A tiny library to support Huawei AppGallery in-app rating/commenting for React-Native

react-native-appgallery A tiny library to support Huawei AppGallery in-app rating/commenting for React-Native With this library you can open the nativ

Apr 28, 2022
A basic movie rating application which created with using Redux Toolkit, Axios for API calls, React Router DOM for Routing and Node-SASS for my SCSS compile to CSS..

A basic movie rating application which created with using Redux Toolkit, Axios for API calls, React Router DOM for Routing and Node-SASS for my SCSS compile to CSS..

May 5, 2022
WebApp to check friend's codechef rating & other details easily.

Codechef Cards A WebApp to check friend's codechef rating and other details. Just add username and track your friends progress!! Press delete to remov

May 1, 2022
Star Admin Free React Template
 Star Admin Free React Template

Star Admin Free React Template Star Admin React is yet another incredible admin template from BootstrapDash that is based on Bootstrap framework. The

Apr 29, 2022
STAR WARS web page using the SWAPI API information build with React
STAR WARS web page using the SWAPI API information build with React

Star Wars Página web de STAR WARS usando la información de la API SWAPI. La web desarrollada es una web con información sobre las naves de Star Wars y

Feb 18, 2022
Star-wars-api - SWAPI project using React and TypeScript
Star-wars-api - SWAPI project using React and TypeScript

Small project using React and TypeScript to start the app use NPM start

Feb 1, 2022