State instead of props
Suppose we want to
change rating by clicking on specified star.
State is similar to props,
but it is private and controlled by component.
When
state changes, the UI is re-rendered to reflect those changes.
Why we use state.rating
instead of props.rating will be more clear later on.
import React, {Component} from 'react';
class Rating extends Component {
constructor(props) {
super(props);
this.state = {rating: this.props.rating};
}
render() {
return (
<div class='rating'>
Rating: {this.state.rating}
</div>
);
}
}
export default Rating;
Handle events
Install React icons library
npm install react-icons --save
Handling events with React components is very similar to handling events on DOM elements.
However, with JSX we pass a function as the event handler, rather than a string.
Note that we have five different rating components each having their own local state.
Each updated independently.
import React, {Component} from 'react';
import { IoIosStar, IoIosStarOutline} from 'react-icons/io';
class Rating extends Component {
constructor(props) {
super(props);
this.state = {rating: this.props.rating};
}
handleClick(ratingValue) {
this.setState({rating: ratingValue});
}
render() {
return (
<div class='rating'>
Rating: {this.state.rating}
{this.state.rating >= 1 ?
(<IoIosStar onClick={this.handleClick.bind(this,1)} />) :
(<IoIosStarOutline onClick={this.handleClick.bind(this,1)} />)}
{this.state.rating >= 2 ?
(<IoIosStar onClick={this.handleClick.bind(this,2)} />) :
(<IoIosStarOutline onClick={this.handleClick.bind(this,2)} />)}
</div>
);
}
}