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) { /* Look here */
/* add functionalities that includes state management */
super(props); /* Look here */
this.state = {rating: this.props.rating};
}
render() {
return (
<div class='rating'>
Rating: {this.state.rating} /* look here */
</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) {
// add functionalities that includes state management
super(props);
this.state = {rating: this.props.rating};
}
// state is private
handleClick(ratingValue) {
this.setState({rating: ratingValue});
}
render() {
// this.props.rating (from <Rating rating="1"> in App.js)
return (
<div class='rating'>
Rating: {this.state.rating} /* Look Here */
{this.state.rating >= 1 ? /* Look Here */
(<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)} />)}
//... to 5
</div>
);
}
}
Last update: 496 days ago