If you work with React framework and willing to expand your skills I recommend to start using Marerial UI. Marerial Ui is a library of React components for faster and easier web development which is going to save your time on writing code. There are plenty of elements and components that you can integrate to your project. Here are some examples:
Today I would like to do a small tutorial about 5 -Star Rating Component from Material UI. For installation you only need to run 1 command:
npm install material-ui-rating
It will appear as a dependency in your package.json
import Rating from 'material-ui-rating'
in your component where are you going to integrate Rating.
For creating a Rating simply include <Rating/> with properties you need. On example below I wrote User Component with integrated Rating .
class User extends Component {
render() {
return (
{this.props.user.avatar}
{this.props.user.name}
<Rating value = {2}
size = "small"
readOnly />
)}}
There are the most useful properties for <Rating/> component:
precision = {number}
— the minimum increment value change allowed,
value = {number}
— the rating value,
readOnly
— removes all hover effects and pointer events.
onChange = {value => this.changeHandler(value)}
onCnange
property is necessary for implementing Rating where users can actually rate something. Lets create it!
- Ensure don’t include
readOnly
to <Rating/> component, it sets to false by default and the Rating is going to have a hover effect.
2. Add changeHandler property which changes a state of Component.
class User extends Component {
state={
ratingValue: 0
}changeHandler = value => {
this.setState({
ratingValue: value
})
}render() {
return (
{this.props.user.avatar}
{this.props.user.name}
<p>Rate this user<p/>
<Rating value = {this.state.ratingValue}
size = "small"
onChange = {value => this.changeHandler(value)} />
)}}
By clicking on a star they turn yellow (not on this picture though).
3. Next step is to POST or PATCH rating to your Database, depends on how the backend of your app set up. Rating can be as an attribute(array) of User Model or separate Rating Model. The second way gives you opportunity to show the users who rate. If you decided to go with Rating as User attribute, ensure to include :array => true
to your User table.
create_table :users do |t|
t.string :first_name
t.string :avatar
t.integer :rating, :array => true
end
Thank you for reading!