ShakaCode | ShakaCode Blog | Rails On Maui Blog | Rails | ReactJs | JavaScript | Webpack | Productivity |

Uncaught TypeError: Cannot read property 'setState' of undefined


#1

Hi i am trying to displaying start rating ,But i get a error
Error is : Uncaught TypeError: Cannot read property ‘setState’ of undefined

class Foo extends Component {
changeRating( newRating, name ) {
this.setState({
rating: newRating
});
}

render() {
return (
<StarRatings
rating={this.setState.rating}
starRatedColor=“blue”
changeRating={this.changeRating}
numberOfStars={5}
name=‘rating’
starDimension=“20px”
starSpacing=“8px”
/>
);
}
}

How to solve this .
Please help me


#2

You should bind the changeRating() method to the component class instance (this) directly or indirectly. You can do this adding a constructor like:

constructor(props) {
  super(props);
  this.changeRating = this.changeRating.bind(this);
}

or by replacing changeRating() function definition with the arrow function like:

const changeRating = (newRating, name) => {
   ...
}

All the details are in the official documentation: https://reactjs.org/docs/handling-events.html (search for .bind(this)).

Or you can switch to the latest and greatest in the React world - React Hooks - and forgot about this altogether.