star-rating-react-ts
TypeScript icon, indicating that this package has built-in type declarations

1.1.4 • Public • Published

React Star Rating Component

A super simple, tiny, customizable star rating React component that installs no additional dependencies, has a total size of 11KB and has Typescript support.

Working examples can be found here Star Rating Examples

How to use

Requirements:

React >= 16.8.0

Install:

On the command line navigate to the project root and enter

npm install star-rating-react-ts

Import:

import {StarRating} from 'star-rating-react-ts'

JSX:

<YourComponent>
    <StarRating/>
</YourComponent>

Props

prop name type default optional description
numStars number 5 true number of stars to display
initialRating number 0 true initial rating value
readOnly boolean false true ignore user interaction
theme object see below true styling options
onClick function undefined true called when the user clicks a star, receives the new star rating as an argument (number)
icon JSX.Element undefined true a custom SVG icon imported as a React Component

Theming

Schema and default values for the theme prop object (all properties are optional):

{
    colors: {
        backgroundDefault: 'lightgray',
        backgroundColorActive: '#D8A127',
        backgroundColorHover: '#275ed8'
        }
    },
    size: 50
}

Custom Icons

By default the star rating component displays a star icon SVG. To use a custom icon in the star rating:

  1. The SVG needs to be imported as a React Component. The easiest option is to use SVGR. Create React App includes SVGR under the hood. Vite publishes a simple SVGR plugin that can be installed in your project. In the following example it is assumed that the SVG icon file is in an assets folder in the src folder within the project root:

App.tsx

// Using Create React App
import { ReactComponent as BoneIcon } from './assets/bone.svg';

// Using the SVGR plugin for Vite
import BoneIcon from "./assets/bone.svg?react";

function App () {
    ...
    return <StarRating icon={<BoneIcon/>}/> // <-- pass custom icon as a component!
}
  1. In the SVG image file, add the following fill & width attributes to the opening <svg> tag to ensure the theme colors and size props are inherited.

bone.svg

<svg xmlns="http://www.w3.org/2000/svg"
     fill="currentColor"
     width="100%"
...
</svg>

Accessibility

In addition to standard mouse and touch events this component is designed to be compatible with assistive technology (ie screen readers) and keyboard navigation. We use Axe Dev Tools to test for accessibility.

Package Sidebar

Install

npm i star-rating-react-ts

Weekly Downloads

19

Version

1.1.4

License

MIT

Unpacked Size

19.5 kB

Total Files

8

Last publish

Collaborators

  • overtureweb