Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active December 16, 2018 01:56
Show Gist options
  • Save harrisonmalone/940a7ea9d5af595533932c7284ac2abf to your computer and use it in GitHub Desktop.
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
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;
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