Repository: cameronroe/react-star-rating
Branch: master
Commit: f602aa883d93
Files: 17
Total size: 26.4 KB
Directory structure:
gitextract_jpsz708p/
├── .eslintrc
├── .gitignore
├── .jshintrc
├── .npmignore
├── LICENSE
├── README.md
├── changelog.md
├── index.html
├── package.json
├── postcss.config.js
└── src/
├── StarRating.js
├── assets/
│ └── react-star-rating.sketch
├── docs.html
├── docs.js
├── sass/
│ ├── demo.scss
│ └── react-star-rating.scss
└── utils.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .eslintrc
================================================
{
"parser": "babel-eslint",
"ecmaFeatures": {
"arrowFunctions": true,
"templateStrings": true,
"classes": true,
"modules": true,
"restParams": true,
"jsx": true
},
"env": {
"browser": true,
"node": true,
"es6": true
},
"globals": {
"BROWSER": true
},
"rules": {
"quotes": 0,
"no-trailing-spaces": 0,
"no-unused-vars": 0,
"no-alert": 0,
"strict": 0
}
}
================================================
FILE: .gitignore
================================================
node_modules
bootstrap-star-rating
./src/components/Review.jsx
other
.travis.yml
coverage
dist
test
karma.conf.js
webpack.config.js
================================================
FILE: .jshintrc
================================================
{
"curly": true,
"eqeqeq": true,
"immed": true,
"latedef": true,
"newcap": false,
"noarg": true,
"sub": true,
"undef": true,
"unused": true,
"boss": true,
"eqnull": true,
"expr": true,
"node": true,
"browser": true,
"devel": true,
"esnext": true
}
================================================
FILE: .npmignore
================================================
node_modules
bootstrap-star-rating
other
test
karma.conf.js
webpack.config.js
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2015 Cameron J Roe
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# react-star-rating 
[](https://nodei.co/npm/react-star-rating/)

> A simple star rating component built with React.
## Install
```sh
$ npm install react-star-rating --save
```
Include the css:
```html
```
## Usage
### ES6
```js
import React from 'react';
import StarRating from 'react-star-rating';
class FormComponent extends React.Component {
render() {
return (
);
}
}
React.render(, document.getElementById('star-rating'));
```
### ES5
```js
var React = require('react');
var StarRating = require('react-star-rating');
var FormComponent = React.createClass({
render: function () {
return (
);
}
});
React.render(, document.getElementById('star-rating'));
```
## Options
- **name**={string} - name for form input (required)
- **caption**={string} - caption for rating (optional)
- **totalStars**={number} - rating amount (required, default: 5)
- **rating**={number} - a set rating between the rating amount (optional)
- **disabled**={boolean} - whether to disable the rating from being selected (optional)
- **editing**={boolean} - whether the rating is explicitly in editing mode (optional)
- **size**={number} - size of stars (optional)
- **onRatingClick**={function} - a handler function that gets called onClick of the rating (optional) - gets passed (event, {position, rating, caption, name})
## Todo
- [x] Fix ES6 bug with bundling
- [x] Add svg stars
- [x] Double-check touch support works
- [ ] Re-implement star hovering (kinda janky right now)
## License
[MIT](https://github.com/cameronjroe/react-star-rating/blob/master/LICENSE)
================================================
FILE: changelog.md
================================================
## v1.4.0 - 10.10.15
- Changed ratingAmount to totalStars
- Added SVG stars
- Updated to React 0.14.x
- Temporarily removed step support while react updates mask attribute
================================================
FILE: index.html
================================================
React Star Rating
================================================
FILE: package.json
================================================
{
"name": "react-star-rating",
"version": "1.4.2",
"description": "A simple star rating component built with React.",
"main": "./dist/react-star-rating.min.js",
"scripts": {
"start": "npm run dev",
"dev": "webpack serve",
"build": "webpack",
"test": "karma start ./test/karma.conf.js",
"prepublish": ""
},
"repository": "cameronroe/react-star-rating",
"license": "MIT",
"dependencies": {
"classnames": "^2.3.2",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
"devDependencies": {
"@babel/core": "^7.19.6",
"@babel/preset-env": "^7.19.4",
"@babel/preset-react": "^7.18.6",
"autoprefixer": "^10.4.13",
"babel-eslint": "^10.1.0",
"babel-loader": "^9.0.0",
"chai": "^4.3.6",
"cross-env": "^7.0.3",
"css-loader": "^6.7.1",
"eslint": "^8.26.0",
"eslint-webpack-plugin": "^3.2.0",
"html-webpack-plugin": "^5.5.0",
"isparta": "^3.0.4",
"istanbul-instrumenter-loader": "^2.0.0",
"jshint-stylish": "^2.2.1",
"karma": "^6.4.1",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^3.1.1",
"karma-coverage": "^2.2.0",
"karma-mocha": "^2.0.1",
"karma-phantomjs-launcher": "^1.0.4",
"karma-sinon": "^1.0.5",
"karma-sourcemap-loader": "^0.3.8",
"karma-webpack": "^5.0.0",
"mocha": "^10.1.0",
"node-bourbon": "^4.2.8",
"node-sass": "^7.0.3",
"postcss": "^8.4.18",
"postcss-loader": "^7.0.1",
"react-addons-test-utils": "^15.6.2",
"sass": "^1.55.0",
"sass-loader": "^13.1.0",
"sinon": "^14.0.1",
"style-loader": "^3.3.1",
"through2": "^4.0.2",
"vinyl-source-stream": "^2.0.0",
"webpack": "^5.74.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.11.1",
"webpack-shell-plugin-next": "^2.2.2"
}
}
================================================
FILE: postcss.config.js
================================================
module.exports = {
plugins: [
require('autoprefixer')
]
}
================================================
FILE: src/StarRating.js
================================================
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import cx from 'classnames';
import { utils } from './utils';
import './sass/react-star-rating.scss';
function isFloat(n) {
return n === Number(n) && n % 1 !== 0;
}
// TODO
// - Add support for svg symbol
// - Add svg masking when react supports it
// - Update onClick to onSelect which supports mobile, desktop
// - Add onChange to trigger function when rating changes
/**
* @fileoverview react-star-rating
*
*/
class StarRating extends Component {
// static propTypes = {
// name: React.PropTypes.string.isRequired,
// caption: React.PropTypes.string,
// totalStars: React.PropTypes.number.isRequired,
// rating: React.PropTypes.number,
// onRatingClick: React.PropTypes.func,
// disabled: React.PropTypes.bool,
// editing: React.PropTypes.bool,
// size: React.PropTypes.number
// }
static defaultProps = {
step: 1,
totalStars: 5,
onRatingClick() {},
disabled: false,
size: 50,
rating: 0
}
constructor(props) {
super(props);
this.state = {
currentRatingVal: props.rating,
currentRatingPos: this.getStarRatingPosition(props.rating),
editing: props.editing || true,
rating: props.rating,
pos: this.getStarRatingPosition(props.rating),
glyph: this.getStars(),
size: props.size
};
}
componentWillMount() {
this.min = 0;
this.max = this.props.totalStars || 5;
if (this.props.rating) {
this.state.editing = this.props.editing || false;
}
}
componentDidMount() {
this.root = ReactDOM.findDOMNode(this.refs.root);
this.ratingContainer = ReactDOM.findDOMNode(this.refs.ratingContainer);
}
componentWillUnmount() {
delete this.root;
delete this.ratingContainer;
}
/**
* Gets the stars based on totalStars
* @return {string} stars
*/
getStars() {
var stars = '';
var numRating = this.props.totalStars;
for(var i = 0; i < numRating; i++) {
stars += '\u2605';
}
return stars;
}
getWidthFromValue(val) {
var min = this.min,
max = this.max;
if (val <= min || min === max) {
return 0;
}
if (val >= max) {
return 100;
}
return (val - min) * 100 / (max - min);
}
calculate(pos) {
var val = utils.getValueFromPosition(pos, this.props.step, this.ratingContainer, this.min, this.max),
width = this.getWidthFromValue(val);
width += '%';
return {width, val};
}
getStarRatingPosition(val) {
return this.getWidthFromValue(val) + '%';
}
getRatingEvent(e) {
let root = this.root;
let pos = utils.getPosition(e, root);
return this.calculate(pos);
}
/**
* Get Star SVG
*/
getSvg(rating) {
let stars = [];
for (let i = 0; i < this.props.totalStars; i++) {
let attrs = {};
attrs['transform'] = `translate(${i*50}, 0)`;
attrs['fill'] = (i+this.props.step <= rating) ? '#FFA91B' : '#C6C6C6';
stars.push(
);
}
let styles = {
width: `${stars.length * this.props.size}px`,
height: `${this.props.size}px`
};
return (
);
}
/**
* Update the active rating selection
* @param {number} width width based on mouse position
* @param {number} val current rating amount
*/
updateRating(width, val) {
this.setState({
pos: width,
rating: val
});
}
/**
* Update rating state if props have changed
*/
shouldComponentUpdate(nextProps, nextState) {
if (nextProps !== this.props) {
this.updateRating(
this.getStarRatingPosition(nextProps.rating),
nextProps.rating
);
return true;
} else {
return nextState.currentRatingVal !== this.state.currentRatingVal || nextState.rating !== this.state.rating;
}
}
/**
* Set position to original state
*/
handleMouseLeave() {
this.setState({
pos: this.state.currentRatingPos,
rating: this.state.currentRatingVal
});
}
/**
* Update position to current event state
* @param {object} event
*/
handleMouseMove(e) {
// get hover position
let ratingEvent = this.getRatingEvent(e);
this.updateRating(
ratingEvent.width,
ratingEvent.val
);
}
/**
* Update rating state, Trigger function handler
* @param {object} event
*/
handleClick(e) {
if (this.props.disabled) {
e.stopPropagation();
e.preventDefault();
return false;
}
var payload = {
currentRatingPos: this.state.pos,
currentRatingVal: this.state.rating,
caption: this.props.caption,
name: this.props.name
};
this.setState(payload);
this.props.onRatingClick(e, {
rating: this.state.rating,
position: this.state.pos,
caption: this.props.caption,
name: this.props.name
});
}
getClasses() {
return cx({
'rsr-root': true,
'rsr--disabled': this.props.disabled,
'rsr--editing': this.state.editing
});
}
getCaption() {
if (this.props.caption) {
return ({this.props.caption});
} else {
return null;
}
}
setAttrs(isState) {
let attrs = {};
if (isState) {
attrs['onMouseMove'] = this.handleMouseMove.bind(this);
attrs['onMouseLeave'] = this.handleMouseLeave.bind(this);
attrs['onClick'] = this.handleClick.bind(this);
}
return attrs;
}
render() {
let classes = this.getClasses();
let caption = this.getCaption();
let attrs = this.setAttrs(this.state.editing);
return (
{caption}
{this.getSvg(this.state.rating)}
);
}
}
export default StarRating;
================================================
FILE: src/docs.html
================================================
<%= htmlWebpackPlugin.options.title %>
================================================
FILE: src/docs.js
================================================
import React, { Component } from 'react';
import { createRoot } from 'react-dom/client';
import StarRating from './StarRating';
import pkg from '../package';
import './sass/demo.scss';
const inject = document.querySelector('.inject');
const root = createRoot(inject);
class Docs extends Component {
handleRatingClick(e, data) {
console.log(data);
alert('You left a ' + data.rating + ' star rating for ' + data.name);
}
render() {
var currentVersion = pkg.version;
return (
rating{'={number} - a set rating between the rating amount (optional)'}
disabled{'={boolean} - whether to disable the rating from being selected (optional)'}
editing{'={boolean} - whether the rating is explicitly in editing mode (optional)'}
size{'={number} - size of stars (optional)'}
onRatingClick{'={function} - a handler function that gets called onClick of the rating (optional) - gets passed (event, {position, rating, caption, name})'}
Examples
{'// handler in react class'}
{'handleRatingClick: function (e, data) {'}
{' alert(\'You left a \' + data.rating + \' star rating for \' + data.caption);'}
{'}'}
{' '}
{''}
{'If you\'re using ES6, make sure to bind the handler: '}{'this.handleRatingClick.bind(this, pass, args, here)'}