Skip to content

Instantly share code, notes, and snippets.

@powerwlsl
Created February 25, 2018 05:03
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 powerwlsl/494f9267b4b9164f52551a45abde619e to your computer and use it in GitHub Desktop.
Save powerwlsl/494f9267b4b9164f52551a45abde619e to your computer and use it in GitHub Desktop.
import 'react-dates/initialize';
import 'react-dates/lib/css/_datepicker.css';
import React from 'react';
import moment from 'moment';
import { SingleDatePicker } from 'react-dates';
const now = moment().format('MMM Do, YYYY');
export default class ExpenseForm extends React.Component {
constructor(props) {
super(props)
this.state = {
description: props.expense ? props.expense.description : '',
note: props.expense ? props.expense.note : '',
amount: props.expense ? (props.expense.amount / 100).toString() : undefined,
createdAt: props.expense ? moment(props.expense.createdAt) : moment(),
calendarFocused: false,
error: undefined
};
}
onDescriptionChange = (e) => {
const description = e.target.value;
this.setState(() => ({ description }));
}
onNoteChange = (e) => {
const note = e.target.value;
this.setState(() => ({ note }));
}
onAmountChange = (e) => {
const amount = e.target.value;
if (!amount || amount.match(/^\d{1,20}(\.\d{0,2})?$/)) {
this.setState(() => ({ amount }));
}
}
onDateChange = (createdAt) => {
if (createdAt) {
this.setState(() => ({ createdAt }))
}
}
onFocusChange = ({ focused }) => {
this.setState(() => ({ calendarFocused: focused }))
}
onSubmit = (e) => {
e.preventDefault();
if (!this.state.description || !this.state.amount) {
this.setState(() => ({ error: "can't be blank"}))
} else {
this.setState(() => ({ error: undefined}))
this.props.onSubmit({
description: this.state.description,
amount: parseInt(this.state.amount, 10) * 100,
createdAt: this.state.createdAt.valueOf(),
note:this.state.note
})
}
}
render() {
return (
<div>
{this.state.error && <p>Error! {this.state.error}</p>}
<form onSubmit={this.onSubmit}>
<input
type="text"
placeholder="Description"
autoFocus
value={this.state.description}
onChange={this.onDescriptionChange}
/>
<input
type="number"
placeholder="Amount"
value={this.state.amount}
onChange={this.onAmountChange}/>
<textarea
placeholder="Add a note for your expense"
value={this.state.note}
onChange={this.onNoteChange}
>
</textarea>
<SingleDatePicker
date={this.state.createdAt} // momentPropTypes.momentObj or null
onDateChange={this.onDateChange} // PropTypes.func.isRequired
focused={this.state.calendarFocused} // PropTypes.bool
onFocusChange={this.onFocusChange}
numberOfMonths={1} // PropTypes.func.isRequired
isOutsideRange={() => false}
/>
<button>Add expense</button>
</form>
</div>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment