Last active
December 16, 2018 01:56
-
-
Save harrisonmalone/940a7ea9d5af595533932c7284ac2abf to your computer and use it in GitHub Desktop.
nice example of using state in react, in this case every click updates the count attribute associated with each animal in the zoo array of animal objects
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
import React, { Component } from 'react' | |
class Animal extends Component { | |
constructor(props) { | |
super(props) | |
} | |
clickAnimal() { | |
this.props.updateCount(this.props.name) | |
} | |
render() { | |
return ( | |
<button onClick={this.clickAnimal.bind(this)}>{this.props.name} {this.props.emoji}</button> | |
) | |
} | |
} | |
export default Animal; |
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
import React, { Component } from 'react'; | |
import './App.css'; | |
import Animal from './Animal.js' | |
class App extends Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
zoo: [ | |
{ | |
name: 'Bear', | |
emoji: 'π»', | |
count: 0, | |
continent: 'North America' | |
}, | |
{ | |
name: 'Tiger', | |
emoji: 'π―', | |
count: 0, | |
continent: 'Asia' | |
}, | |
{ | |
name: 'Turtle', | |
emoji: 'π’', | |
count: 0, | |
continent: 'Oceania' | |
}, | |
{ | |
name: 'Snake', | |
emoji: 'π', | |
count: 0, | |
continent: 'Africa' | |
}, | |
{ | |
name: 'Fish', | |
emoji: 'π ', | |
count: 0, | |
continent: 'Oceania' | |
} | |
], | |
continentsArr: [] | |
} | |
} | |
updateCount(animalName) { | |
const { zoo } = this.state | |
const foundAnimal = zoo.find((animalObj) => animalObj.name === animalName) | |
foundAnimal.count++ | |
this.setState({ zoo }) | |
} | |
render() { | |
const { zoo } = this.state | |
return ( | |
<div className="App"> | |
{zoo.map((animal) => { | |
return ( | |
<div key={animal.name}> | |
<h1>{animal.count}</h1> | |
<Animal name={animal.name} emoji={animal.emoji} updateCount={this.updateCount.bind(this)} /> | |
</div> | |
) | |
})} | |
</div> | |
); | |
} | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment