Âu Hải

1 bundle
1 file7 months ago
1

Untitled

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
import React, { Component } from 'react'; import './MonthOption.scss'; import moment from 'moment'; import YearView from 'react-calendar'; const MONTH = ['0', 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] const DATE_PATTERN = 'MM/DD/YYYY'; class MonthOption extends Component { constructor(props) { super(props); this.state = { curentMonth: moment(new Date()), isShowCalendar: false, dateInCustomCalendar: new Date(), monthChosen: null } this.handleChangeMonth = this.handleChangeMonth.bind(this); this.onClickCalendar = this.onClickCalendar.bind(this); } componentDidMount(){ const { curentMonth } = this.state; this.setState({ monthChosen: curentMonth.format(DATE_PATTERN) }, () => { document.getElementById(this.state.monthChosen).classList.add('active'); }) } handleChangeMonth(e) { const { monthChosen, dateInCustomCalendar } = this.state; const element = e.target; document.getElementById(monthChosen).classList.remove('active'); element.classList.add('active'); this.setState({ isShowCalendar: _.isEqual(element.id, 'custom') ? !this.state.isShowCalendar : false, dateInCustomCalendar: _.isEqual(monthChosen, 'custom') ? dateInCustomCalendar : new Date(monthChosen), monthChosen: element.id, }, () =>{ if(!_.isEqual(element.id, 'custom')){ this.props.onChangeMonth(this.state.monthChosen); } }); } renderButtonMonth(id, content) { return ( <button id={id} className="btn btn-outline-primary" onClick={this.handleChangeMonth} key={id} > {content} </button> ) } renderMonthItems() { const { curentMonth } = this.state; const listMonthItems = []; _.forEach([4, 3, 2, 1], i => { const month = moment(curentMonth).subtract(i, 'M'); const content = i == 1 ? 'Last Month' : `${MONTH[parseInt(month.format('M'))]} - ${month.format('YYYY')}`; const id = month.format(DATE_PATTERN); listMonthItems.push(this.renderButtonMonth(id, content)); }); listMonthItems.push(this.renderButtonMonth(curentMonth.format(DATE_PATTERN), 'Current Month')); listMonthItems.push(this.renderButtonMonth('custom', 'Custom')); return listMonthItems; } onClickCalendar(date){ this.setState({ isShowCalendar: false, dateInCustomCalendar: date }, () => { this.props.onChangeMonth(moment(date).format(DATE_PATTERN)); }); } render() { const { isShowCalendar, dateInCustomCalendar } = this.state; return( <div className="month-wrapper clearfix"> <div className="title">Show history in</div>{' '} <div role="group" className="btn-group"> { this.renderMonthItems() } </div> { !isShowCalendar ? null : ( <div className="calendar"> <YearView value={dateInCustomCalendar} view={'year'} onClickMonth={this.onClickCalendar} /> </div> ) } </div> ) } } export default MonthOption;