Skip to content

Instantly share code, notes, and snippets.

@pixeline
Created August 28, 2019 18:51
Show Gist options
  • Save pixeline/68ce2058a8e2aa09701318a34b97c906 to your computer and use it in GitHub Desktop.
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 ?
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>
)
}
}
@pixeline
Copy link
Author

pixeline commented Sep 2, 2019

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