Code is a countdown timer.
Should I keep this update function separate as is or can I save 3 lines of code and embed this.setState({newDeadline: event.target.value})
directly in the callback function below? eg. onChange={event => this.setState({newDeadline: event.target.value}}
import React, { Component } from 'react';
import './App.css';
import Clock from './Clock';
import {FormGroup, FormControl, Button} from 'react-bootstrap';
class App extends Component {
constructor(props) {
super(props);
this.state = {
deadline: 'December 25 2017',
newDeadline: ''
}
}
updateDeadline() {
if (isNaN(Date.parse(this.state.newDeadline)) || this.state.newDeadline === '') {
this.setState({deadline: this.state.deadline});
} else {
this.setState({deadline: this.state.newDeadline})
}
}
updateNewDeadline(event) {
this.setState({newDeadline: event.target.value})
}
render() {
return (
<div className="app">
<div className="app-title">Countdown To {this.state.deadline}</div>
<Clock deadline={this.state.deadline} />
<form className="app-form">
<FormGroup>
<FormControl className="deadline-input"
placeholder='Enter a new date'
onChange={event => this.updateNewDeadline(event)}
/>
<Button bsStyle="primary" block onClick={() => this.updateDeadline()}>Submit</Button>
</FormGroup>
</form>
</div>
)
}
}
export default App;
1 Answer 1
My two takes in this. In you example your are creating a new event handler on each render, so if you want to do it that way you would for sure want to bind the event handlers in the constructor. But if your never re-using them and it doesent clutter up the JSX "markup" to much (e.g. just a clean setState) I am always using the inline setState
like you suggested:
import React, { Component } from 'react';
import './App.css';
import Clock from './Clock';
import {FormGroup, FormControl, Button} from 'react-bootstrap';
class App extends Component {
constructor(props) {
super(props);
//Bound event handlers
this.updateNewDeadline = this.updateNewDeadline.bind(this);
this.updateDeadline = this.updateDeadline.bind(this);
this.state = {
deadline: 'December 25 2017',
newDeadline: ''
}
}
updateDeadline() {
if (isNaN(Date.parse(this.state.newDeadline)) || this.state.newDeadline === '') {
this.setState({deadline: this.state.deadline});
} else {
this.setState({deadline: this.state.newDeadline})
}
}
updateNewDeadline(event) {
this.setState({newDeadline: event.target.value})
}
render() {
return (
<div className="app">
<div className="app-title">Countdown To {this.state.deadline}</div>
<Clock deadline={this.state.deadline} />
<form className="app-form">
<FormGroup>
<FormControl className="deadline-input"
placeholder='Enter a new date'
onChange={this.updateNewDeadline}
/>
<Button bsStyle="primary" block onClick={this.updateDeadline}>Submit</Button>
</FormGroup>
</form>
</div>
)
}