GithubHelp home page GithubHelp logo

awran5 / react-simple-star-rating Goto Github PK

View Code? Open in Web Editor NEW
125.0 2.0 30.0 1.48 MB

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

Home Page: https://react-simple-star-rating.vercel.app/

License: MIT License

TypeScript 89.61% CSS 2.77% JavaScript 7.61%
star-rating react react-typescript react-library

react-simple-star-rating's Introduction

React Simple Rating

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

NPM JavaScript Style Guidenpm bundle sizeGitHub

screenshot

Install

npm

npm i react-simple-star-rating

Yarn

yarn add react-simple-star-rating

Usage

import React, { useState } from 'react'
import { Rating } from 'react-simple-star-rating'

export function MyComponent() {
  const [rating, setRating] = useState(0)

  // Catch Rating value
  const handleRating = (rate: number) => {
    setRating(rate)

    // other logic
  }
  // Optinal callback functions
  const onPointerEnter = () => console.log('Enter')
  const onPointerLeave = () => console.log('Leave')
  const onPointerMove = (value: number, index: number) => console.log(value, index)

  return (
    <div className='App'>
      <Rating
        onClick={handleRating}
        onPointerEnter={onPointerEnter}
        onPointerLeave={onPointerLeave}
        onPointerMove={onPointerMove}
        /* Available Props */
      />
    </div>
  )
}

Reset Rating Value

import React, { useState } from 'react'
import { Rating } from 'react-simple-star-rating'

export function MyComponent() {
  const [rating, setRating] = useState(0)

  // Catch Rating value
  const handleRating = (rate: number) => {
    setRating(rate)
  }

  const handleReset = () => {
    // Set the initial value
    setRating(0)
  }

  return (
    <div className='App'>
      {/* set initial value */}
      <Rating onClick={handleRating} initialValue={rating} />

      <button onClick={handleReset}>reset</button>
    </div>
  )
}

Available Props

Prop Type Options Description Default
onClick function Optional callback with hover, index and event values passed -
onPointerMove function Optional callback with hover, index and event values passed -
onPointerEnter function Optional callback with event passed -
onPointerLeave function Optional callback with event passed -
initialValue number Optional Set initial value 0
iconsCount number Optional Number of the icons 5
readonly boolean Optional Readonly mode false
rtl boolean Optional RTL mode false
transition boolean Optional Adds a smooth transition effect on mouse hover false
allowFraction boolean Optional Enable a fractional icon (half icon) false
className string Optional Applied to the main span react-simple-star-rating
style CSSProperties Optional Inline style applied to the main span basic style
size number Optional SVG Icon width / height in px 25
SVGstrokeColor string Optional SVG Icon stroke color currentColor
SVGstorkeWidth string | number Optional SVG Icon storke width 0
SVGclassName string Optional SVG Icon css class star-svg
SVGstyle CSSProperties Optional SVG inline style -
fillIcon ReactNode Optional Custom fill icon SVG null
fillColor string Optional Fill icons color #f1a545
fillColorArray array Optional Array of string to add color range []
fillStyle CSSProperties Optional Inline style applied to filled icon span basic style
fillClassName string Optional Applied to the filled icon span filled-icons
emptyIcon ReactNode Optional Custom empty icon SVG null
emptyColor string Optional Empty icons color #cccccc
emptyStyle CSSProperties Optional Inline style applied to empty icon span basic style
emptyClassName string Optional Applied to the empty icon span empty-icons
customIcons array of object Optional Add a group of icons []
allowHover boolean Optional Enable / Disable hover effect true
disableFillHover boolean Optional Enable / Disable hover effect on filled stars false
allowTitleTag boolean Optional Enable / Disable HTMLtitle Tag true
showTooltip boolean Optional Show a tooltip with live values false
tooltipDefaultText string Optional Initial tooltip text if no rating value Your Rate
tooltipArray array Optional Array of strings to show inside tooltip []
tooltipClassName string Optional Tooltip CSS class rating-tooltip
tooltipStyle CSSProperties Optional Inline style applied to the tooltip span basic style
titleSeparator string Optional Separator word in a title of a rating star (1 out of 5) out of


BREAKING CHANGES: version 4.1.0 (2022-10-03)

old new changes
allowHalfIcon allowFraction Renamed
fullIcon fillIcon Renamed
fullStyle fillStyle Renamed
fullClassName fillClassName Renamed
ratingValue - Removed

Demos

See all demos and usage examples in action.


Edit react-simple-rating-ts

License

MIT ยฉ awran5

react-simple-star-rating's People

Contributors

awran5 avatar brycefranzen avatar esaracco avatar github-actions[bot] avatar jiwooincludejeong avatar juwain 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

react-simple-star-rating's Issues

Change default custom tooltip when no rate selected

Hello!
First, thank you so much for this amazing library, it is really helpful and the doc is just super clear.

I am using the custom tooltip feature, and this is working great. I have used an array to set the message for each rate as below :

const tooltipArray = ['Terrible ๐Ÿ˜ช', 'Bad ๐Ÿ˜', 'Average ๐Ÿ˜•', 'Great ๐Ÿ˜Š', 'Perfect ๐Ÿ˜']

However, when no rate is selected, there is a default tooltip as you can see below :
image

Is there a way to customize it ?

Unable to give rating in integer value

Need a way to give rating in integer only without disabling allowedFraction.
When allowedFraction is enabled, it also shows half filled stars on hover. There should be a way to show stars filled completely on hover when even allowedFraction is enabled.

Doesn't work on mobile browsers

Hello,
I've tried it on my website and it doesn't work on mobile browsers (iOS, Chrome and Safari).
Demo doesn't work either.

[v4] Display vertically by default

Thanks so much for this project!

I just installed it but the v4 is rendering the stars vertically, so it's not usable. If I install version 3.0.0 it works as expected.

Add Icon Margin Request / Wrong Rating shown

Problem: if you want to add custom margin to your icons you can't do it properly.
You can set margin on the icon itself, like wrap it in another span and give it a margin, but that will brake the precision of the icons shown.

Here is the example: I've given a marginRight to my custom icon and I've set initialValue to 3.5:
image

I can give a padding to my custom icon and it will correctly show values with .5 , but if we have .2 or .7 it will not look precisely.

I assume that right now this library simply creates 2 divs one with empty and one with filled icons and later on based on the initialValue make them overlap to some extend.

So, if you make a margin between icons it will brake the precision.

My suggestion is to fill each icon separately:
If initialValue is for example 3.3 - it will fill each icon separately: 3 will be filled and one will be filled only for 30%. This will still work if you have 10 icons.
Also, we will need to add new properties to the lib: iconMarginRight & iconMarginLeft - which will enable developers to set custom margins on the icon.

Let me know if this can be implemented.

init stars on mouse leave

For better UI/UX stars should be as init selected after of mouse out (leave).

Assume stars are init of 2 of 5. when users hovered on the other stars then seems selected (this is ok). But when mouse out entirly of block of stars (and without click in one of the stars). it should be selected as before of hovering. But this not happen

Its not problem with state managment, even if I set the init by new state (useState) the stars remains selected of the last hover (except if unmount and mount entire component).

I think this is a bug or a UI/UX gap. How to solve this ? or waiting for a new verion ?

No way to clear rating

How can I clear the rating back to the initial empty state? Previously I could use ratingValue to clear when clicking the current rating:

  const handleRating = (value: number) => {
    if (value === rating) {
      setRating(0);
    } else {
      setRating(value);
    }
  };

But with the removal of ratingValue in v4.1.0 I'm no longer sure how to do this.

Please let me know if there is another way to clear the rating on the latest version!

The Rating component behaves the same way with or without Transition

<Rating
        onClick={(e) => {}}
        ratingValue={5}
        size={20}
        fillColor="orange"
        className="foo" // Will remove the inline style if applied
     />
     
     

and

<Rating
        onClick={(e) => {}}
        ratingValue={5}
        size={20}
        fillColor="orange"
        transition
        className="foo" // Will remove the inline style if applied
      />

Behaves the same way

Rating is loading 10 stars on refresh then quickly returning to 5 stars

                 <Rating
                     iconsCount={5}
                     size={25}
                     ratingValue={0}
                     transition
                     allowFraction
                     readonly
                     initialValue={element}
                     fillColor="#D32748"
                   />

element is a tempory value just to see it working but it ranges from anywhere between 1 and 4, but it always loads as 5 out of 10 stars no matter what for a split second which messes up the layout with the increased height then quickly fixes itself. Any ideas what im doing wrong?

Ratings broken!

Thanks for lib :)

Just trying to implement it using floating values for 5 star rating component. Doesnt seem to work. It weird that for 5 it somehow is taking as 0.5 or less (if you look closely)

<Rating
                  className="flex"
                  ratingValue={5}
                  readonly
                  transition
                  size={20}
                  allowHalfIcon
                  fillColorArray={[
                    "#f17a45",
                    "#f19745",
                    "#f1a545",
                    "#f1b345",
                    "#f1d045",
                  ]}
                />

image

Not sure, what I am doing wrong

Stars not filled on iPhone

Hello,
Thanks a lot for the amazing library.

I have noticed on iPhone only the stars are not filled in yellow in static mode (readOnly) when displaying the rate.
Please see the screenshot attached.

It works perfectly on Android phone, the issue appears only on iphone.
Any idea what's happening?

image

Thanks!

Unable to click on stars in React testing library.

How can i clicks on the star rating. I tried so much.
<div className="text-center mt-3"> <Rating initialValue={rating} onClick={handleRating} fillColor={surveyTheme?.mainThemeColor || "#F1A900"} fillIcon={ <RxStarFilled size={50} aria-label="filled-stars" role="button" /> } emptyIcon={ <RxStar size={50} color={surveyTheme?.mainThemeColor || "#F1A900"} aria-label="unfilled-stars" role="button" /> } allowHover={false} aria-label="ranking-stars" as="button" /> </div>

Please make this accessible

It's not currently possible to navigate this component with just your keyboard. For the vision impaired, it makes this unusable. Thanks!

v4.1.0 doesn't include dist/ on npm

When downloading v4.1.0 from npm, only the following files are included:

react-simple-star-rating/
โ”œโ”€โ”€ LICENSE
โ”œโ”€โ”€ README.md
โ””โ”€โ”€ package.json

Also please take a look at semver.org. Because of the breaking API Changes, this update should have been a major release.

Can't reset ratingValue

I have the rating as a part of a form, which when submitted eventually resets the star rating but the rating is not being reactive:

const handleReview = (e) => { ... setRating(0); ... };

<Rating allowHalfIcon onClick={handleRating} ratingValue={rating} />

Is there a different way to do this?

readonly

readonly is not working and how to disable rating if it's needed

Installation failed in react 18.2.0

There is peer dependency error for react 18.2.0

I like to ask whether there are any trouble by installing with --force command and also updating plan for current react version.
npm ERR! Could not resolve dependency: npm ERR! peer react@"^16 || ^17" from [email protected] npm ERR! node_modules/react-google-login npm ERR! react-google-login@"^5.2.2" from the root project npm ERR! npm ERR! Conflicting peer dependency: [email protected] npm ERR! node_modules/react npm ERR! peer react@"^16 || ^17" from [email protected] npm ERR! node_modules/react-google-login npm ERR! react-google-login@"^5.2.2" from the root project

Is there a way to turn off the hover alt text '18.75 out of 4' ?

Hi there!

I would like to use this component and adjust the iconsCount to less than 5. However, the alt text is calculated as percentages by default. So instead of 3 out of 4 given iconsCount of 4, it displays as 18.75 out of 4 (which is quite confusing for the user).

image

Here is the code used:

<Rating
    onClick={handleRating2}
    transition
    iconsCount={4}
    size={50}
/>

Please advise! Thank you!

Stars appearing vertically

I am using tailwind css in my project and after I installed tailwind I am experiencing a vertical alignment of stars

Can someone help me sort this out.

Error when installing

Tried installing this today as this is the best star rating system i've found and get a bunch of errors
image

initialValue is not working

initialValue={5}
it does not respect that, and initially it is showing as blank only with no stars filled, even with readonly settings.

Rating of more than 5 icons doesn't behave as expected

I used the codesandbox demo to try out the project. Amazing project and thank you for this!

I wanted to have 10 star IMDb style rating on my website. I set iconsCount={10} but it doesn't look like the tooltipArray and fillColorArray are respected when there are more than 5 stars. For example, even on full rating, it still shows 5 out of 10.

image

This is the code

const tooltipArray = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"];  

const fillColorArray = [
  "#f17a45",
  "#f17a45",
  "#f19745",
  "#f19745",
  "#f1a545",
  "#f1a545",
  "#f1b345",
  "#f1b345",
  "#f1d045",
  "#f1d045"
];  

<Rating
    onClick={handleRating1}
    ratingValue={rating1}
    size={50}
    iconsCount={10}
    allowHover
    transition
    showTooltip
    tooltipArray={tooltipArray}
    fillColorArray={fillColorArray}
  />

Cannot rate in mobile browser

Rating works fine on web browser but i am unable to rate in a mobile browser. I notice it works fine in the working examples provided so I am suspecting it is happening with new version.

Using this widget in a loop - Causes issue

I have a usecase where I need the rating for multiple trips that a customer has taken. I am trying to use this in a loop.

When the page is loaded -> useEffect is called and feedbackdetails are loaded for multiple rides. I loop feedbackdetails to render the stars for each ride.

When user submits 3 star for one and clicks on 'Submit Feedback' button, the feedback is submitted correctly but the second ride automatically gets the (same) 3 star rating.

The way I am storing the rating in state is like {index: rating}, but I am resetting it after each loadFeedbackDetails. loadFeedbackDetails will return only the rides that aren't submitted for feedback.

Can someone explain why is this the case?
I am resetting -- setRating({}); when the axios.get happens and I am setting initialValue to initialValue={rating[index] || 0}

Have been stuck on this issue since 2 days.


const [rating, setRating] = useState({});

const handleRating = (rate: number, index: number) => {
let tempRating = rating;
tempRating[index] = rate;
console.log(tempRating);
setRating(tempRating)
}

function loadFeedbackDetails() {
    setFeedLoading(true);
    axios.get(process.env.REACT_APP_API + '/feedback/' + session.userId)
        .then((axiosResponse1: AxiosResponse) => {
            setRating({});
            setFeedLoading(false);
            setfeedbackDetails(axiosResponse1.data);
        })
        .catch((reason: AxiosError) => {
          // TBD
        })
}

function submitFeedBack(item: any, index: number) {
axios.post(process.env.REACT_APP_API + '/feedback?' + 'rating=' + rating[index])
.then((axiosResponse1: AxiosResponse) => {
setRating({});
console.log(axiosResponse1.data);
loadFeedbackDetails();
})
.catch((reason: AxiosError) => {
// TBD
})
}

useEffect(() => {
    loadFeedbackDetails();
}, []);

{feedbackDetails.map((item, index) => (

{

                                <IonCardContent>
                                   
                                    <p>Rate your trip!</p>
                                    <p>
                                        <Rating initialValue={rating[index] || 0} transition={true}
                                            onClick={(event) => handleRating(event, index)} />
                                                {/* <Rating style={{ maxWidth: 200 }} value={rating[index] || 0} onChange={(event: number) => handleRating(event, index)} /> */}


                                    </p>
                                   

                                    <p> <IonButton color="success" onClick={() => submitFeedBack(item, index)} class="feedbackbutton">Submit Feedback</IonButton>
                                      

                            }

                        </IonCard>
                    ))}

Unable to select the last star

Hello, I use tailwind and I have a problem.
I used SVGclassName="inline-block" to no longer have the stars vertical. it works but I have a problem in the selection, it is impossible for me to select the last star (unless I reduce the size of the window by half or increase the size of Rating).

I did the test of disabling Tailwind on the whole project, and I get normal Rating behavior.
Do you have a solution ?
ratingbug

Thanks

Window is not defined error

I'm using version 5.1.2 with Next.js but the error Server Error ReferenceError: window is not defined is thrown when trying to use this component. I'm aware this was a closed issue but the problem has not been resolved.

Cant reset rating from click on star

I am trying to build a rating system where you can reset the rating back to 0 by clicking on whatever star has already been set to the current value. For example, if a rating is showing 4 / 5 stars, clicking on the 4th star would remove the rating entirely.

I am using the initialValue prop and a controlled input as suggested,but the stars do not reset visually even though the state changes. I also built in a secondary button to test out the function and it it capable of clearing the rating.

Is there any way around this? Tried using a timeout and that didn't work

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.