dreyescat / react-rating Goto Github PK
View Code? Open in Web Editor NEWA rating react component with custom symbols.
Home Page: http://dreyescat.github.io/react-rating/
License: MIT License
A rating react component with custom symbols.
Home Page: http://dreyescat.github.io/react-rating/
License: MIT License
The example for an svg element is not working. http://dreyescat.github.io/react-rating/
I can not use the new release because of this bug.
Add an optional clear button that clears the rating, and falls back to the placeholder rating if one exists.
Example:
http://plugins.krajee.com/star-rating-demo-theme-svg#theme-svg-ltr-star
Not sure if this would cause any other problems, I can attempt a PR if you like.
The reason I would like it is that I'm working on a project where we show a popover when a user rates something, but the mouseDown is triggering the rating and the mouseUp is being caught by the (now visible) popover and closing it.
I feel like it is more in line with what I would expect anyway - if I mouse down and then change my mind about the rating I want to give, dragging to the correct rating and doing a mouse up then would fire the desired rating.
Let me know your thoughts :)
With increasing emphasis on making websites accessible to people with disabilities it is good time to make this component A11y compatible too. Not having A11y support has both business and legal impact.
For rating, there's a fine example at W3C WAI Custom Controls.
If you are fine with it I am planning to do that on v1. I am asking to do it on v1 as it has backward compatibility implications as it would require me to change each StarSymbol's span to input type="radio". Alternatively I can keep span and put role radio but it would require custom keyboard handling to be implemented which is not advisable especially for cases where a native control is available.
Could you update the dependencies for React 15 please?
Unable to find proper documentation for changing the default icon, can any one help out ?
I want to create a rating labelled with numbers of corresponding rate.
Something like this: [1][2][3][4]
"empty" and "full" elements are custom React components, so I am using component this way:
<Rating
start = {0}
stop = {4}
onChange = {rate => this.applyRate(rate, index)}
empty = {<EmptyRating/>}
full = {<FullRating/>}
/>
But I cant figure out how to access corresponding rate number from my "EmptyRating" and "FullRating" components.
Is there any way to achieve it?
Lines 158 to 163 in 8043bbc
Since getBoundingClientRect() can return sub-pixel values and clientX/Y are always rounded off, it causes flicker while mouse moves from one star to next for 1 pixel. I was able to fix this by using Math.floor on values returned by getBoundingClientRect().
It would be nice if the rating component could be used in some sort of a ‘calm’ mode, i.e. not change the number of stars, circles, etc. when a mouse moves over it. This mode would be something like the readonly
mode, but with callbacks enabled.
Can be reproduced in
http://dreyescat.github.io/react-rating/
Alert when rate changes
Open chrome, emulate as iphone X
click on any symbol except first
you will get two alerts.
First of all, love the design of this component! Simple and straight forward as it should be.
I don't have much criticism other than the fact that it would be great if you could change the fill colors of the stars. Here's an example:
I wouldn't say you need all the options like other rating systems. No need for stroke color etc on the stars, just would be great to change the base fill color.
When rating, if I place the cursor right between, say, 4th and 5th stars, both will be empty while the first 3 are full, same for 3rd and 4th start with first 2 etc. It's a very small problem, but makes the rating look buggy. I'm using material design icons, but it also happens with the default icon. Looks like there's some sort of border around the icons, but it does not show when inspecting the elements. Any advice?
Gotta remove CreateClass prior to version 16. Seems to only be in 4 files:
https://github.com/dreyescat/react-rating/search?utf8=%E2%9C%93&q=React.CreateClass&type=
PercentageSymbol: React.createClass is deprecated and will be removed in version 16. Use plain JavaScript classes instead. If you're not yet ready to migrate, create-react-class is available on npm as a drop-in replacement.
Hi,
it's not a big deal but on this line there is a basic w3c validation issue
https://github.com/dreyescat/react-rating/blob/master/src/PercentageSymbol.jsx#L60
"Element div not allowed as child of element span"
would you consider changing it to span?
We use react-rating in readonly mode a lot, but we are receiving warnings for the mouse and touch events as they seem to get passed to the child as boolean false instead of null as would be expected. eg: Warning: Expected 'onMouseLeave' listener to be a function, instead got a value of 'boolean' type.
It looks like the cause is the checks for readonly here: https://github.com/dreyescat/react-rating/blob/master/src/Rating.jsx#L172 - those expressions return false.
I have some custom logic in my function used for onChange
where based on some condition, I want to alter the resulting value (specifically, setting it back to what it was). I think a slight change to the API of this would enable me to do this as well as enabling more customizability of this library in general:
If the signature for this function was changed to:
(value, oldValue) => value
And this library applied the return value to the UI (e.g. if my logic changes the value from 8 to 4, the rating component updates to reflect that as if the user selected 4 themselves) I would be able to implement what I'm going for. If the return could be a Promise that gets awaited before updating the UI would be even more ideal.
My specific use-case is that I want to measure body.scrollTop
to see if the user is attempting to scroll vertically (scrollTop
has changed compared to a previous measurement), and if so I want to revert the rating value back to what it was (since the user intended to scroll, not to rate)
This is a follow-up of #49.
It's been almost two years since this component came to life. It started out when React versions where 0 based. It survived the 0.14.x
to 15
transition and now, with the coming of a new major release, it makes it necessary to evolve to the new standards to not become obsolete.
This also presents a new opportunity for improvement in:
How to change stars etc? Give examples please.
Are you going to update this? Nothing works. No props work. fractions does nothing.
Whenever I set callback like onClick
then as a user I can't set rating.
import React from 'react';
import Types from 'prop-types';
import ReactRating from 'react-rating';
import '../_styles/Rating.scss';
const Rating = ({ initialRate, modifier, onClick, readOnly }) => (
<div className={`Rating ${modifier}`}>
<ReactRating
onClick={onClick}
initialRate={5}
empty="fa fa-star-o"
full="fa fa-star"
readonly={readOnly}
/>
</div>
);
Rating.propTypes = {
initialRate: Types.number,
modifier: Types.oneOf(['', '--center-big']),
onClick: Types.func,
readOnly: Types.bool,
};
Rating.defaultProps = {
initialRate: 5,
modifier: '',
onClick: () => null,
readOnly: false,
};
export default Rating;
EDIT:
I found out that whenever I change state in container component and re-render happens, the initialRate
is set again:
onStarsClick = nr => {
if (nr > 0) {
this.setState({ stars: nr, userInteracted: true, });
}
};
render() {
if (!userState.feedbackToken) {
return null;
}
const { stars, submitted, showPopover, userInteracted } = this.state;
return (
<div className="FeedbackChat">
{
showPopover &&
<div className="feedback-popover">
{submitted ?
<div className="thank-u">
<p>Thank you and good luck!</p>
</div>
:
<span>
<FeedbackHeading onStarsClick={this.onStarsClick} />
</span>
}
</div>
}
</div>
);
}
I added code below in my jsx
<Rating onClick={rating => this.handleRate(rate)} />
and browser console says the rate is not defined. How should I define this rate variable? Or how can I interact with this component to get user's rate value?
Sorry for such a dumb question and it will be nice to help me with this problem. Thanks in advance.
Hi,
Can you please add RTL support ?
The half stars doesn't look good on RTL .
Regards,
Yaniv
I have just migrated to 1.0.1 and this error is printed in console regarding internal props:
Warning: Failed prop type: Invalid prop `onClick` of type `boolean` supplied to `RatingSymbol`, expected `function`.
in RatingSymbol (created by Rating)
in Rating (created by RatingAPILayer)
in RatingAPILayer (created by Rated)
...
This is also printed:
Warning: Failed prop type: Invalid prop `onMouseMove` of type `boolean` supplied to `RatingSymbol`, expected `function`.
in RatingSymbol (created by Rating)
in Rating (created by RatingAPILayer)
in RatingAPILayer (created by Rated)
...
Is this package support to rate half star ?
I have a component A which imports and uses the Rating component from react-rating. If I use this component A in my application, there is no issue.
But lately, I started to create my own component library and I moved component A into this library. Now, I have the following error:
invariant.js?da6c:44 Uncaught (in promise) Error: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created inside a component's
render method, or you have multiple copies of React loaded (details: https://fb.me/react-refs-must-have-owner)
If I remove the code where I use the Rating component from my component A, the error disappear. I tried to add react-rating in the "externals" array of my webpack config, but it didn't help.
Any idea on how to fix that?
I cannot initialize negative rates. For example, using a [-2, 3) range, rates from -2 to 0 are ignored.
The code below shows the rating element empty.
<Rating start={-2} stop={3} initialRate={-1} />
Check jsfiddle.
I need to call event.stopPropogation(), but onClick event passes only rating value..
e.g. <Rating readonly={true} initialRate={value} style={{color: 'orange'}} empty="glyphicon glyphicon-star-empty" full="glyphicon glyphicon-star" fractions={2} />
Here is example for reproduce:
https://codesandbox.io/s/oj7mzzww36
I debug it... Problem is that RatingAPILayer
PureComponent
shouldComponentUpdate
does not handle checking for react element. So, on every onHover execution, RatingAPILayer
will be rerendered which cause multiple rerendering. Another problem is in Rating
component componentWillReceiveProps
:
componentWillReceiveProps(nextProps) {
this.setState({
dirty: this.props.value !== nextProps.value && !this.state.dirty
? true
: this.state.dirty,
displayValue: nextProps.value
});
}
I do not understand why on every props update displayValue
is set to nextProps.value
. But if shouldComponentUpdate
is handled properly in RatingAPILayer
this is not a problem.
The demo page does not show any of the rating elements. Only the headers are shown. Console shows the following error messages:
GET http://dreyescat.github.io/react-rating/node_modules/font-awesome/css/font-awesome.css
GET http://dreyescat.github.io/react-rating/node_modules/bootstrap/dist/css/bootstrap.css
GET http://dreyescat.github.io/react-rating/node_modules/react/dist/react.js
react-rating.js:338 Uncaught TypeError: Cannot read property 'createClass' of undefined
at Object.<anonymous> (react-rating.js:338)
at __webpack_require__ (react-rating.js:31)
at Object.module.exports (react-rating.js:74)
at __webpack_require__ (react-rating.js:31)
at Object.assign.i (react-rating.js:60)
at __webpack_require__ (react-rating.js:31)
at react-rating.js:51
at react-rating.js:54
at webpackUniversalModuleDefinition (react-rating.js:10)
at react-rating.js:11
Uncaught ReferenceError: ReactRating is not defined
at (index):95
When the user clicks on the stars for the first time, it's not firing the onChange or onRate function.
I couldn't set the initialRate to a fraction and see partial stars, after more digging i found out the problem in the indexOf function and to be more specific the use of Math.floor
i changed this
return Math.max(Math.floor((rate - range.start) / step), 0);
to
return Math.max(((rate - range.start) / step).toFixed(1), 0);
Not really sure if it will break anything though
This component can't cancel rate if user rated.
To solve this, rate
props is needed.
With new React upgrade all tests are failing. Below the two different errors:
1) PercentageSymbol with inline icon and background style "before each" hook for "should have inline styled background":
TypeError: TestUtils.createRenderer is not a function
at render (test/PercentageSymbol-test.js:8:28)
at Context.<anonymous> (test/PercentageSymbol-test.js:21:16)
PercentageSymbol
with inline icon and background style
1) "before each" hook for "should have inline styled background"
with class name icon and background style
2) "before each" hook for "should have class styled background"
with 25 percent icon
3) "before each" hook for "should show 25% icon width"
Is there a way to go from ★☆☆☆☆ to ☆☆☆☆☆?
Being able to click the first star a second time and remove the rating entirely would be really nice.
Probably some resources have been moved and the demo page fails to find them.
Failed to load resource: the server responded with a status of 404 (Not Found) react.development.js
Failed to load resource: the server responded with a status of 404 (Not Found) react-dom.development.js
Hi, I'm having issues after doing a setState within onClick...there are no errors, the state is set, but the elements in the view are not being filled, the span style for all filled elements has width: 0%
I did a workaround by defining a global "let score" instead of using setState but I know that is not a good solution.
render()
<div className="rate-wrap">
<Rating
empty={"icon-star-filled"}
full={"icon-star-filled active"}
onChange={this.handleScore}
/>
</div>
handleScore(s) {
// score is global, it should be this.setState({score:s}); but doesn't work
score = s;
}
What am I doing wrong?
Thanks!
Sebastian
Hi mate,
Good stuff with the react-rating, i'm trying to use it in my project but this particular instance of placeholder rating is not working, here's my code:
<Rating initialRate={ratingAvg} empty="glyphicon glyphicon-star-empty star-grey fs-xl" placeholder="glyphicon glyphicon-star-empty star-red fs-xl" placeholderRate={ratingAvg} full="glyphicon glyphicon-star star-yellow fs-xl" />
it should display yellow stars by default and on hover it should display red ones, right?
using that code, the stars are always in 'full' mode, in yellow, they don't turn to placeholder red as specified.
Any ideas?
Thanks
When using this component on mobile, the user can select the first symbol and then swipe right to select a value (ie touch and drag).
When a user drags past the last symbol, and then releases, the rating value returned from the component is higher than the max value allowed by the props passed in.
Here is an example from your example page. I am swiping on the rating symbols and dragging PAST the last symbol.
Code breaks on React 16 since the propTypes
have been removed from the default react
variable.
Code needs to change to use propTypes
from the prop-types
package
Source
react-rating/src/RatingAPILayer.jsx
Line 1 in 02fdc27
Hi,
I feel like onHover is missing from the callbacks of your component (which my team and I have been using for a year now, thanks a lot!). It could pass the value of the hovered score, and would be useful to display some text under the Rating Component, to explain the meaning of each score.
Please let me know if you want do it or if I should do a PR.
Thanks for your work!
Could you please provide an example on how to use the 'placeholder' prop? Regardless how I'm trying to use it, it has no effect. Eg
placeholder={width: "32px", height: "32px"}
or
placeholder={<div className="red"></div>}
or
placeholder="<div></div>"
It doesn't matter how I slice it, whatever I place into 'placeholder' is not showing up when I inspect the elements in the browser. An example would be helpful.
Thanks!
Hello!
I want to user ReactRating component together with styled-components and style root component a little bit. But this is not possible because remaining properties like className
are not passed to the root component. Also would be great if there is a possibility to choose root component type.
Great simple project btw :) Cheers!
So in my use case, i have a Rating component where i show the average score for a given product, and whenever a user clicks on a specific rate, a prompt to leave comments opens with another Rating component showing the given rate, BUT the first Rating component should go back to the average score.
While checking through closed issues i found #16 so i took those lines to set up my desired behaviour resulting in this:
Which works exactly as it is supposed to, but on mobile, the first Rating component keeps showing the last clicked rating until i click somewhere else:
There's no activeElement after the onChange, i´ve forked the fiddle on the mentioned (#16) issue to replicate this behaviour and it behaves the same, works on desktop, not on mobile:
https://jsfiddle.net/jandramila/k11mcb8v/3/
Any thoughts or workarounds?
I'm running into an issue where the underlying Rating
component's state.displayValue
is getting updated incorrectly.
Here is a Codepen demonstrating the problem: https://codepen.io/joekrill/pen/NyeKpL
Note that hovering an icon momentarily, then moving the mouse out of the component completely continues to show the last hovered item instead of reverting back to the current value. This can vary a bit depending on how quickly the mouse is moved - if you're not seeing this behaviour try moving the mouse more slowly. Here's a gif of what I'm seeing (I'm not clicking anything at all here, just moving the mouse):
This only seems to happen in some very specific scenarios. For example, doing any of the following will cause things to work "as expected":
initialRating
prop, or setting it to zero (0
)fullSymbol
and emptySymbol
props, or setting them to a string, or even precreating their components.Ultimately I think the problem is that in the Rating
component's componentWillReceiveProps
method, setState
is called by passing a new state object directly, and is using a reference to the current state (this.state.displayValue
, in this particular case, line 5 below):
componentWillReceiveProps(nextProps) {
const valueChanged = this.props.value !== nextProps.value;
this.setState({
dirty: valueChanged || this.state.dirty,
displayValue: valueChanged ? nextProps.value : this.state.displayValue
});
}
However, per the the React docs, setState
calls of this type are asynchronous and may be batched together. In this particular case, this can cause this.state.displayValue
to be set based on an out-of-date previous displayValue
. Which is why it is recommended that the updater function form of setState
be used instead. So this should really be:
componentWillReceiveProps(nextProps) {
const valueChanged = this.props.value !== nextProps.value;
this.setState((prevState) => ({
dirty: valueChanged || prevState.dirty,
displayValue: valueChanged ? nextProps.value : prevState.displayValue
}));
}
And indeed that seems to fix the problem in my testing.
So I think when props are changed in a certain way that causes componentWillReceiveProps
to get called very soon after onMouseLeave
, the setState
calls get batched causing the wrong displayValue
to get calculated.
I'm still a little confused as to why exactly it is that certain things - like not setting initialRating
- prevent the problem. But that doesn't really change the fact that this setState
call should be using an updater function since it's setting the new state based on the previous state. So I'll put up a PR for that at least.
When I try
<Rating empty={<img src="emptystar.svg" />} full={<img src="fullstar.svg" /> placeholder={<img src="fullstar.svg" />} placeholderRate={2.8} />
when the placeholderRate in decimal place of 0.1, 0.2 , 0.8 and 0.9,
it will occurs check sum issues in Microsoft Edge browser and IE
Warning: React attempted to reuse markup in a container but the checksum was invalid. This generally means that you are using server rendering and the markup generated on the server was not what the client was expecting. React injected new markup to compensate which works but you have lost many of the benefits of server rendering. Instead, figure out why the markup being generated is different on the client or server:
(client) dth:79.99999999999998%;" data-reactid=".
(server) dth:79.99999999999999%;" data-reactid=".
it work fine in other browser.
Please fix the bugs. Thank you!!!
I find the current documentation very difficult to decipher. On the demo page you supply various icons using SVG, span element, image, color ratings, fontawesome icons, etc, but you don't provide any sample of how to set these up and how to use them.
Under "properties" there's one called "placeholder" and another called "full". Both has the default value "Style.full" listed. What does that mean? I have to create a style called ".full"? I don't know what they refer to.
I understand that the documentation makes perfect sense to you, but it can be very confusing due to lack of details and samples.
I'm importing the module with
var Rating = require('react-rating');
That alone (without using the component anywhere) causes the main component in the file not to call the ComponentDidMount function. It renders properly, except for the properties this function should provide.
It also causes this warning, whether or not I instantiate a Rating component:
Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.
<Rating
stop={10}
fractions={2}
onClick={this.submitRating.bind(this, this.props.id)}
/>;
I have used both the onChange and onClick methods but still I have to click a 2nd time for it to return a value. Please what is going on?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.