Created
December 31, 2017 16:24
-
-
Save chausen/cceb2397b8cd7d6c3b2ca27442148ee2 to your computer and use it in GitHub Desktop.
React Clock List with Add
This file contains 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
class Clock extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = {date: new Date()}; | |
} | |
componentDidMount() { | |
this.timerID = setInterval( | |
() => this.tick(), | |
1000 | |
); | |
} | |
componentWillMount() { | |
clearInterval(this.timerID) | |
} | |
tick() { | |
this.setState({ | |
date: new Date() | |
}); | |
} | |
render() { | |
return ( | |
<div> | |
<h1>Hello, world!</h1> | |
<h2>It is {this.state.date.toLocaleTimeString()}.</h2> | |
</div> | |
); | |
} | |
} | |
function Button(props) { | |
return ( | |
<button onClick={props.action}> | |
{props.label} | |
</button> | |
); | |
} | |
class App extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { clocks: [<Clock />] } | |
this.addClock = this.addClock.bind(this); | |
} | |
addClock(e) { | |
this.setState((prevState, props) => ({ | |
clocks: prevState.clocks.concat([<Clock />]) | |
})); | |
} | |
render() { | |
return ( | |
<div> | |
<h1>List of Clocks</h1> | |
<Button action={this.addClock} label="Add Clock"/> | |
{this.state.clocks} | |
</div> | |
); | |
} | |
} | |
ReactDOM.render( | |
<App />, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment