javascript - Allow user to rate from 0.5 to 5 -
i have made rating component user can rate there problem. user can rate 0 4.5(0, 0.5, 1, 1.5 till 4.5) unexpected behavior, instead, want user rate 0.5 till 5. how make so? here component star rating
here workaround
https://codesandbox.io/s/9y14x3704
class rating extends react.component { constructor(props) { super(props); this.state = { rating: props.defaultrating || null, maxrating: props.maxrating || null, temp_rating: null }; } componentwillreceiveprops(nextprops) { if (nextprops.defaultrating !== this.props.defaultrating) { this.setstate({ rating: nextprops.defaultrating, maxrating: nextprops.maxrating }); } } handlemouseover(rating) { this.setstate(prev => ({ rating: rating / 2, temp_rating: prev.rating })); } handlemouseout() { // this.state.rating = this.state.temp_rating; // this.setstate({ rating: this.state.rating }); this.setstate(prev => ({ rating: prev.temp_rating })); } rate(rating) { this.setstate( { rating: rating / 2, temp_rating: rating / 2 }, () => this.props.handlerate(this.state.rating) ); } render() { const { rating } = this.state; let stars = []; (let = 0; < 11; i++) { let klass = "icon-star-o"; if (this.state.rating >= / 2 && this.state.rating !== null) { klass = "icon-star"; } stars.push( <i style={{ display: "inline-block", width: "10px", overflow: "hidden", direction: % 2 === 0 ? "ltr" : "rtl" }} classname={klass} key={i} onmouseover={() => this.handlemouseover(i)} onclick={() => this.rate(i)} onmouseout={() => this.handlemouseout()} /> ); } return <div classname="rating">{stars}</div>; } } const props = { defaultrating: 2, maxrating: 5, handlerate: (...args) => { console.log(args) } } reactdom.render(<rating {...props} />, document.queryselector('.content'))
.rating{ border: 1px solid gray padding: 5px; } i[class^='icon-star'] { border: 1px solid black; margin: 4px; padding: 5px; height: 10px; } .icon-star { background: gray; } .icon-star-o { background: yellow; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div class='content'></div>
can me @ this, please?
i've changed count until 10 , reversed stars
here's updated render()
method:
render() { const { rating } = this.state; let stars = []; (let = 1; <= 10; i++) { /* note starting @ 1 until 10 */ let klass = "fa fa-star-o"; if (rating >= / 2 && rating !== null) { klass = "fa fa-star"; } stars.push( <i style={{ display: "inline-block", width: "8px", overflow: "hidden", direction: % 2 ? "ltr" : "rtl" /* reverse half stars */ }} classname={klass} key={i} onmouseover={() => this.handlemouseover(i)} onclick={() => this.rate(i)} onmouseout={() => this.handlemouseout()} /> ); } return <div classname="rating"> {stars}<br /> {rating} </div>; }
Comments
Post a Comment