Created
August 28, 2019 18:51
-
-
Save pixeline/68ce2058a8e2aa09701318a34b97c906 to your computer and use it in GitHub Desktop.
Pure React, Chapter 11: Exercise at the end of the chapter. Is this a proper react way to pass the ID to the state ?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const Room = ({onAction, room, children}) =>( | |
<button id={room} onClick={onAction} >{children}</button> | |
) | |
class House extends React.Component { | |
state = { | |
rooms: { | |
kitchen: true, | |
bathroom: false, | |
livingRoom: true, | |
bedroom: false | |
} | |
} | |
switchLight = (action)=>{ | |
let key = action.target.id; | |
let newVal = !this.state.rooms[key]; | |
this.setState( (state,props) => { | |
let newRooms = {...this.state.rooms}; | |
newRooms[key]= newVal; | |
return { | |
rooms: {...newRooms} | |
} | |
}); | |
} | |
render(){ | |
return ( | |
<div className="house"> | |
<Room onAction={this.switchLight} room="kitchen">Kitchen</Room> | |
<Room onAction={this.switchLight} room="bathroom">Bath room</Room> | |
<Room onAction={this.switchLight} room="livingRoom">Living Room</Room> | |
<Room onAction={this.switchLight} room="bedroom">Bedroom</Room> | |
<p>Kitchen light: {this.state.rooms.kitchen ? 'on': 'off'}</p> | |
<p>Bathroom light: {this.state.rooms.bathroom ? 'on': 'off'}</p> | |
<p>Living Room light: {this.state.rooms.livingRoom ? 'on': 'off'}</p> | |
<p>Bedroom light: {this.state.rooms.bedroom ? 'on': 'off'}</p> | |
</div> | |
) | |
} | |
} |
Hi @dceddia ! thank you for the feedback!
You mentioned the "updater" form also in the book without really explaining it, It's probably something really simple but I failed to understand what you meant by that. I googled aroundfor it but did not find any reference. Could you perhaps elaborate or point me to a valid source of info?
Thank you again!
A.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is good!
Since you're using the "updater" form of setState on line 18, you can (and should) use
state
in that function instead ofthis.state
, and do any reading of state within that function as well. That's the only thing that stands out as potentially problematic. The intention behind using the function form is to avoid referencing a potentially-stale value ofthis.state
Here's how I'd probably write the
switchLight
function: