Giter VIP home page Giter VIP logo

react-star-rating-component's Introduction

react-star-rating-component

npm version Dependency Status Download Count

Tiny React.js component for star (or any other icon based) ratings.

Install

npm install react-star-rating-component --save

Demo

Props

<StarRatingComponent
    name={String} /* name of the radio input, it is required */
    value={Number} /* number of selected icon (`0` - none, `1` - first) */
    starCount={Number} /* number of icons in rating, default `5` */
    onStarClick={Function(nextValue, prevValue, name)} /* on icon click handler */
    onStarHover={Function(nextValue, prevValue, name)} /* on icon hover handler */
    onStarHoverOut={Function(nextValue, prevValue, name)} /* on icon hover out handler */
    renderStarIcon={Function(nextValue, prevValue, name)} /* it should return string or react component */
    renderStarIconHalf={Function(nextValue, prevValue, name)} /* it should return string or react component */
    starColor={String} /* color of selected icons, default `#ffb400` */
    emptyStarColor={String} /* color of non-selected icons, default `#333` */
    editing={Boolean} /* is component available for editing, default `true` */
/>

Examples

Editable

import React from 'react';
import ReactDOM from 'react-dom';
import StarRatingComponent from 'react-star-rating-component';

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      rating: 1
    };
  }

  onStarClick(nextValue, prevValue, name) {
    this.setState({rating: nextValue});
  }

  render() {
    const { rating } = this.state;
    
    return (                
      <div>
        <h2>Rating from state: {rating}</h2>
        <StarRatingComponent 
          name="rate1" 
          starCount={10}
          value={rating}
          onStarClick={this.onStarClick.bind(this)}
        />
      </div>
    );
  }
}

ReactDOM.render(
  <App />, 
  document.getElementById('app')
);

Non-editable (with custom icons)

import React from 'react';
import ReactDOM from 'react-dom';
import StarRatingComponent from 'react-star-rating-component';

class App extends React.Component {
  render() {
    const { rating } = this.state;

    return (                
      <div>
        <h2>Rating from state: {rating}</h2>
        <StarRatingComponent 
          name="rate2" 
          editing={false}
          renderStarIcon={() => <span></span>}
          starCount={10}
          value={8}
        />
      </div>
    );
  }
}

ReactDOM.render(
  <App />, 
  document.getElementById('app')
);

Check more in examples folder.


MIT Licensed

react-star-rating-component's People

Contributors

amilajack avatar arximughal avatar bhefty avatar capezzuto avatar inakiabt avatar martimax21 avatar maxcmoi89 avatar ronihcohen avatar voronianski avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-star-rating-component's Issues

How to change a custom .png star color?

<StarRatingComponent
name="small-rater"
starCount={5}
value={this.state.rating}
renderStarIcon={()=> <img src="../bla2.png"}/>}
starColor="#ffb400"
onStarClick={this.updateStar}
editing={true}
/>

Hi thanks for this awesome library. I have a question,
made a custom .png star. When i click the star i expect it to either change color or render a clicked star of my own.
However as i follow the readme starColor is the appropriate prop, yet currently it is not working, are there any solution for this? Could it be I'm doing this wrongly?

Thanks in advance

Wrong star rating.

<StarRatingComponent
                        name="app5"
                        starColor="#ffb400"
                        emptyStarColor="#ffb400"
                        value={3.7}
                        renderStarIcon={(index, value) => {
                            return <span className={index <= value ? 'fa fa-star' : 'fa fa-star-o'} />;
                        }}
                        renderStarIconHalf={() => <span className="fa fa-star-half-full" />}
                    />

when rating is 3.7 or 3.2 it will mark 2.5 stars. but if the value is 3.5 exactly it works as expected.

On the phone

Stars are painted when double-clicked

For fix add onTouchStart event in starNodeLabel

Without es6/es5

I'm not using any es6/5 in my react rails app.

var JobFeedback = React.createClass({

  getInitialState(){
    return {
      rating: 1,
    }
  },

  onStarClick(name, value) {
    this.setState({rating: value});
  },


  render(){
    var rating = this.state.rating;
    return(
      <div className="row">
        <div className="medium-7 medium-centered columns">
          <FeedbackRating
            name="rate1"
            starCount={10}
            value={rating}
            onStarClick={this.onStarClick}
          />
          <textarea type="text" rows="5" value=""
          />
        </div>
      </div>
    )
  }

});

Below of issues:

React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of JobFeedback.

Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Check the render method of JobFeedback.

backend.js:8441 Uncaught TypeError: Cannot read property 'props' of undefined

Default star doesn't load on Galaxy S7 devices and below.

Hi there,

On Galaxy S7 devices and below, the default star looks weird (see screenshot).

screen shot 2018-06-04 at 7 49 54 pm

Here is my implementation:

     <StarRating
        name={index.toString()}
        starCount={5}
        value={stars}
        onStarClick={e => onStarClick(e, index)}
        starColor={'#00B4B1'}
        emptyStarColor={'#e0e2e2'}
      />

Thanks in advance,

Sam

How to custom star style

Hello
Thanks for this.
I have a question> how can I change the star style?
I want to increase the font size.
Thanks

Star half Rating for dynamic created field

Hello,

I am using react-star-rating-component for half star rating ,its working correct for static value but when i created my field dynamically and want to half rating its not working correctly

this.state = {
datalan:{}
}
render() {
return (

	{this.state.skill && this.state.skill.slice(0,3).map(function(skills, i){
	return  <div key={i}>
	<div className="form-group row">
	<label className="col-md-4 col-form-label">{skills.keywordval}</label>
	<div className="col-md-8">
	<div style={{fontSize: 26}}>

	<StarRatingComponent
	name={skills.keywordval}
	starColor="#ffb400"
	emptyStarColor="#ffb400"
	value={this.state.keywordval} // i think here is some mistake
	onStarClick={this.onStarClickHalfStar.bind(this)}
	renderStarIcon={(index, value) => {
		return (
		    <span>
			<i className={index <= value ? 'fas fa-star' : 'far fa-star'} />
		    </span>
		);
	    }
	}
	renderStarIconHalf={() => {
	    return (
		<span>
		<span style={{position: 'absolute'}}><i className="far fa-star" /></span>
		<span><i className="fas fa-star-half i" /></span>
		</span>
	    );
	}} />
	</div>
	</div>
	</div>
	</div>
	}, this)}
)}

onStarClickHalfStar(nextValue, prevValue, name, e) {
	const xPos = (e.pageX - e.currentTarget.getBoundingClientRect().left) / e.currentTarget.offsetWidth;
	console.log("xp====:",xPos);
	if (xPos <= 0.5) {
	nextValue -= 0.5;
	}
	console.log('name5: %s, nextValue: %s, prevValue: %s', name, nextValue, prevValue);

	this.setState({datalan:nextValue});
}

Why there are some radio buttons?

There are some radio button.
see this image:
fireshot capture 1 - myeabsen web app - http___localhost_3000_ _performancequestions_step 1

how to get rid of it?

My setting
<StarRatingComponent name={"Test"} value={2} editing={true} />

ignore initialize value={0}

I have more then one 'react-star-rating-component' at one page app.
When select 'value' at FirstOne, the component save it and set this 'value' to Second as initial.

User can hot fix it using value={-1}

const customPrevValue = isEmpty(this.props.selectedAnswers) ? -1 : this.props.selectedAnswers;

  <StarRatingComponent
    name={ratingSelectorName}
    value={customPrevValue}
  />

some code from StarRatingComponent.jsx :

  componentWillReceiveProps(nextProps) {
    const { value } = nextProps;

    if (value != null && (value !== this.state.value)) {  // <-- here the problem?
      this.setState({ value });
    }
  }

Warning from componentWillReceiveProps

Receiving this warning in the console.

Warning: componentWillReceiveProps has been renamed, and is not recommended for use. See https://fb.me/react-async-component-lifecycle-hooks 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.

React error - StarRatingComponent.render(): A valid React element (or null) must be returned.

This error is happening only when I render this in server-side (i.e. refresh the page) and the page keeps spinning. Using client-side rendering works fine.

{ [Invariant Violation: Minified React error #109; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=109&args[]=StarRatingComponent for the full message or use the non-minified dev environment for full errors and additional helpful warnings.] name: 'Invariant Violation', framesToPop: 1 }

The decoded error message is:
StarRatingComponent.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.

Could someone check this and help.

code:

export const renderStars = (rating, styles) => {
  return (<StarRatingComponent
    name="ratingStar"
    starCount={5}
    value={rating}
    editing={false}
    starColor='#FFFFFF'
    emptyStarColor='#ea9a00'
    className={styles.ratingStars}
    onStarClick={() => {return false;}}
    renderStarIcon={(index, value) => {
      return (<div className={styles.starOrange}>
        <i className={index <= value ? `fa fa-star ${styles.fullStarWhite}` : `fa fa-star-o ${styles.emptyStarOrange}`} />
      </div>);
    }}
    renderStarIconHalf={() => <div className={styles.starOrange}>
      <i className={"fa fa-star-half-full"} />
    </div>}
  />);
};

Revert rating to Old value

Hi All,

In my scenario, When the user clicks on the star rating, I am trying to call an API to submit the latest value, All that I want to do is to revert to the original prop value when the API call fails.

My approach ->

I tried to use forwardRef to access all the child functionality and tried to overwrite the value by using the following

  1. this.childRatingComponentRef.current.props.onStarClick(previousValue) => This also fails and I can't even use this because once the rating is updating I am triggering a function in the parent to make an API cal, so if I do this above approach then I will fall in an endless loop ### :(
  2. this.childRatingComponentRef.current.state.value = 1; => Fails nothing happens and the position of the star is retained :(
  3. I did create another method called rollBackToPrevious and I am setting the state to the previous props value. => This also Fails :(

I am not sure on how to update the start component with a value dynamically from parent component.

Can anyone please help me !!!

Thanks in advance.

React 16 Support

In the dependency we've "react": "^15.4.2", this should be moved to the peerDependency to avoid loading conflicting versions.

Node 8 bond really needed?

Hello,
I'm using this component in a react app. I noticed that the package.json bon the node.js version to be >=8.0.0. Is is really necessary?

Thanks.
Simone

Rating is not accessible via tab

Cannot use keyboard tab to access each individual rating input.

Current behavior: pressing tab skips over the entire component.

Desired behavior: tab would jump into the first rating and tab across them, selecting them when enter is pressed.

update npm index.js

something is out of sync with the npm package and the source code.

For example: this commit is missing from the index.js file in the npm package.

npm registry package not updated with source code

Hi, I believe the package in npm does not have the latest code in github. I believe you merged a new pull request but you did not bump the version and publish it. This is causing react to throw warnings because of the prop-types package

Can you sync the npm registry with the latests?

Thanks @voronianski :)

Stars are clickable (and causing a page reload in my case) even if the editing prop is false

Hi,

Stars are clickable (and causing a page reload in my case) even if the editing prop is false.
Is there a way to make stars non-clickable. I tried passing onStarClick={() => {}}
It still didn't work.

My code:

import StarRatingComponent from 'react-star-rating-component';

export const renderStars = (rating, styles) => {
  return (<StarRatingComponent
    name="ratingStar"
    starCount={5}
    value={rating}
    editing={false}
    starColor='#FFFFFF'
    emptyStarColor='#ea9a00'
    className={styles.ratingStars}
    onStarClick={() => {}}
    renderStarIcon={(index, value) => {
      return (<div className={styles.starOrange}>
        <i className={index <= value ? `fa fa-star ${styles.fullStarWhite}` : `fa fa-star-o ${styles.emptyStarOrange}`} />
      </div>);
    }}
    renderStarIconHalf={() => <div className={styles.starOrange}>
      <i className={"fa fa-star-half-full"} />
    </div>}
  />);
};

Thanks

Rendering half stars

Hello!
Thanks for sharing this, it comes in handy. I have a problem though: we would also like to render half star ratings and I don't know how to get it to work. The renderStarIconHalf prop doesn't seem to do anything for me. Here's what I have (taken from the examples):

<StarRatingComponent
    name="rating"
    editing={false}
    starCount={5}
    value={stars}
    renderStarIcon={(index, value) => {
              return <span className={index <= value ? 'fa fa-star' : 'fa fa-star-o'} />;
            }}
    renderStarIconHalf={() => <span className="fa fa-star-half-full" />}
/>

Any ideas?

Editable half stars fails in example

The editable half stars does not work correctly in (the example)[http://voronianski.github.io/react-star-rating-component/example/]

Initial render looks ok, but after changing the rating there's no way to get it back to a half star.

React redux form?

What is the best way to integrate this library to the react redux form?

<Field model='user.rating' >
                        <StarRatingComponent
                            name='user.rating'
                            starCount={5}
                            value={0}
                            id='user.rating'
                        />
                    </Field>

This is what I have but it is not grabbing the data on submit of form.

RTL support

Is there an option to support right to left display, or just reverse the order of stars?

redux-form full compatibility

Hi, I'm using redux-form, but it doesn't seem to work very well the first click. The star component calls the onStarClick and then I update redux state with the correct value, but the stars are not coloring. I've created a demo project replicating this behaviour: https://stackblitz.com/edit/react-7kb6us . After the first click it works pretty well... Any ideas? Thanks

Hover states?

Is it possible to highlight the currently hovered star and previous ones?

Support for half-star rating

'Half-stars', or the ability to show the user that a rating's value is approximately x.5, is a common pattern in UI's. Would this feature be welcome?

Value Prop on star component doesn't update

Hello,
I recently began using the react-star-rating-component in my project and everything so far has begun to go smoothly when dropping the component in except for one small part. I'm using react v15.0.2 and redux v4.4.5. When I pass data down from the redux store into my component and then update that data the react components props update on the fly. However when passing the props down to react-star-rating-component this does not seem to be working properly. It will not update and will simply stay at the initial prop value. To make sure I wasn't doing anything wrong I passed the same prop into a h1 tag <h1>{props.value}</h1> and then updated the value and the data in the h1 tag updated on the fly. This is the same data being passed down into react-star-rating-component but it doesn't seem to want to update.
Here is what is being passed down:

<StarRatingComponent name="reviewRating" starCount={5} editing={false} value={props.value}/>

If you see anything wrong or have any clue as to why the react-star-rating-component does not update please let me know.

Reset to value 0 not working

Hi there,

Thanks a lot for this very handy component. It's great.

I found a little bug and I don't know if you are aware of it. If I reset the props.value to 0 the component does not update. Reason is the if statement in the componentWillReceivePropswhere you have something like if (value && ... and value = 0 result in false.

Would be great if you could correct it.

Thanks and regards
Joel

Console error

Hi i get this message in the console when trying to use this lib:

warning.js:36Warning: You are manually calling a React.PropTypes validation function for the renderStarIconHalf prop on t. This is deprecated and will not work in the next major version. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details.

PR's

Willing to make the following PR's. Which ones would be welcome?

  • Migrate eslint to airbnb from airbnb/base
  • Change spacing to 2 spaces from 4 spaces
  • Add tests

How to use font awesome icon ?

Hello,

Great rating component, but unable to solve this problem . Can you help ?

Tried to implement custom icon like this
renderStarIcon={() => <span><i class="fa fa-bell"></i></span>}

If this is the wrong way - how I implement custom icons ?
renderStarIcon={() => <span></span>}

How to bring icons in between spans ?
Please help me on this

Decimal/Fraction support for this component

Hi

Is it possible to support fractional rating in value field.

For example : if we are getting rating as 4.5 it is only displaying 4 star.

Can we have support for fraction/decimal rating

onStarClick event.stopPropagation ?

I have a case where StarRating is on top of clickable card. And I don't want onStarClick trigger the card's onClick. And how about hover state ?

onStarClick listener in the document

I think the document is outdated regarding the onStarClick listener:

The original:

    onStarClick(name, value) {
        this.setState({rating: value});
    }

The name actually returned the currently selected value, and the value returned the old value.

I think it should be

{
        onStarClick(currentValue,oldValue, name) {
           this.setState({rating: currentValue});
        }
 }

Editable (with half-stars) Not Working

Hi,
while using this npm module for ratings the half star feature is not working ,It's not showing any stars.
I just copied the below code :

renderStarIcon={(index, value) => { return ( <span> <i className={index <= value ? 'fas fa-star' : 'far fa-star'} /> </span> ); }} renderStarIconHalf={() => { return ( <span> <span style={{position: 'absolute'}}><i className="far fa-star" /></span> <span><i className="fas fa-star-half" /></span> </span> ); }} />

React Version Installed:16.7.0
npm version : 6.4.1

Thanks,
Prabhat

Missing style prop

Hey

I think it would be nice if custom styles could be passed via props.
E.g one could change star size with style={{ fontSize: '50px' }}

Any thoughts?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.