Skip to content

Instantly share code, notes, and snippets.

@chausen
Created December 31, 2017 16:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chausen/cceb2397b8cd7d6c3b2ca27442148ee2 to your computer and use it in GitHub Desktop.
Save chausen/cceb2397b8cd7d6c3b2ca27442148ee2 to your computer and use it in GitHub Desktop.
React Clock List with Add
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