Solution: Update the Rating State2:56 with Guil Hernandez
This video covers one way to update the
rating state based on the star a user clicks.
All right, now I'm going to write the event handler that updates 0:00 the rating state based on the star or user clicks. 0:03 I'll call this function handleSetRating, and 0:06 it will take the parameter rating for the rating value. 0:11 Inside the function, I'll update the rating state to the rating 0:16 value passed to the function using this.setState. 0:21 I'll pass setState an object containing the rating state and rating value. 0:26 Now whenever you find yourself assigning a property value 0:33 that matches our property name, you can omit the property value. 0:36 So I could also use the es2015 shorthand here 0:40 by writing just the property name rating inside the object. 0:43 This function will be passed down to each Star component via props, 0:50 and called when a user clicks on a star. 0:55 So in the renderStars function, 0:59 I'll give the Star component a callback prop, named setRating. 1:02 Then use an arrow function to pass it a reference to handleSetRating 1:09 with this.handleSetRating. 1:15 So I'm passing a function which will be called when an onClick event is 1:22 triggered in the Star component. 1:26 When a user clicks on a star, 1:30 the value of the rating state should update according to the star clicked. 1:32 For example, if a user clicks the third star, it will update the rating state 1:36 to three, the four star will update the rating state to four, and so on. 1:41 To accomplish this, I'll use the for 1:45 loop's counter variable, which acts like an index. 1:48 So I'll pass this.handleSetRating, the value of i, 1:53 and since i begins at 0, I'll need to add 1 to make sure 1:59 that the rating state is updated to the correct value, so i + 1. 2:03 Next over in star.js, I'll give the li an onClick event 2:08 that calls the handleSetRating function being passed via the setRating prop 2:13 each time a list item is clicked with props.setRating. 2:18 Okay, I am going to test what I have written so far. 2:23 I'll open up React Dev tools, and 2:26 select one of the star rating components, let's say the first one. 2:28 I see that its initial rating state is 0, but 2:35 when I click on the first star, the state updates to 1. 2:38 Click on the second star and it updates to 2, and so on, good. 2:42 All right, it looks like I'm almost finished. 2:48 Up next, I'll add the selected styles to the stars 2:50 using conditional class rendering. 2:53
You need to sign up for Treehouse in order to download course files.Sign up