Как уменишить код с 3-ех однотипных дивов до 1 функции?

Всем доброго дня. У меня есть вот такой код:

class Order extends Component {
  constructor(props) {
    super(props);

    this.state = {
    date: new Date(),
    time: '',
    morningTime: ['10-00', '10-30', '11-00', '11-30'],
    dayTime: ['12-00', '12-30', '13-00', '13-30', '14-00', '14-30', '15-00', '15-30', '16-00', '16-30'],
    eveningTime: ['17-00', '17-30', '18-00', '18-30', '19-00', '19-30', '20-00'],
    }
  }

  onClick = (event) => {
    this.setState({time: event.target.innerText})
  };

  onChange = date => this.setState({ date });


  render() {
    // const serviceValue = this.props.service || this.props.location.state.service;
    // const priceValue = this.props.price || this.props.location.state.price;
    return(<div>
      <Header/>
      <div className={styles.bodyContainer}>
        <Link to="/onlineRegistration/ourServices/nails">
          <p className={styles.back}>&#60; Назад</p>
        </Link>
        <h3>Расписание</h3>
      <div className={styles.calendarContainer}>
        <Calendar 
          className={styles.calendar}
          onChange={this.onChange}
          value={this.state.date}
        />
        <OrderDate
          value={this.state.date.toDateString()}
          time={this.state.time}
          address={'/orderInfoClient'}
          history={this.props.history}
          // service={serviceValue}
          // price={priceValue}
        />
      </div>
      <div className={styles.time}>
      <div className={styles.morning}>
        <p className={styles.dayTime}>Утро</p>
        {this.state.morningTime.map((time, i) => (
        <button key={i} value={this.state.time} onClick={this.onClick}>
        {time}
        </button> 
        ))}
      </div>
      <div className={styles.day}>
        <p className={styles.dayTime}>День</p>
        {this.state.dayTime.map((time, i) => (
        <button key={i} value={this.state.time} onClick={this.onClick}>
        {time}
        </button> 
        ))}
      </div>
      <div className={styles.evening}>
        <p className={styles.dayTime}>Вечер</p>
        {this.state.eveningTime.map((time, i) => (
        <button key={i} value={this.state.time} onClick={this.onClick}>
        {time}
        </button> 
        ))}
      </div>
      </div>
      </div>
      <Footer/>
    </div>)
  }
}

export default Order;

Как мне его уменьшить и написать одной функцией, чтобы не было копипасты?


Ответы (1 шт):

Автор решения: hu-fo

Работоспособность не проверял.

Внутри Состояния

xxx: [
  {
    name: 'Утро',
    timeArray: ['10-00', '10-30', '11-00', '11-30'],
    style: styles.morning
  },
  {
    name: 'День',
    timeArray: ['12-00', '12-30', '13-00', '13-30', '14-00', '14-30', '15-00', '15-30', '16-00', '16-30'],
    style: styles.day
  },
  {
    name: 'Вечер',
    timeArray: ['17-00', '17-30', '18-00', '18-30', '19-00', '19-30', '20-00'],
    style: styles.evening
  },
]

Внутри render

const yourComponents = this.xxx.map(({ name, timeArray, style }) => (
  <YourComponent
   style       = {style}
   array       = {timeArray}
   staticStyle = {styles.dayTime}
   time        = {this.state.time}
   onClick     = {this.onClick}
  >{name}</YourNComponent>
));

Внутри return

.... 
{ yourComponents }
....

Компонент

function YourComponent({style, staticStyle, time, array, onClick, children}) {

  const onClickHandler(e) => onClick(e)

  const buttons = array.map((time, i) =>
    (<button key={i} value={time} onClick={onClickHandler}>{ t }</button>)

  return (
    <div className={style}>
      <p className={staticStyle}>{children}</p>
      {buttons}
    </div>
  )
}

И всё равно это выглядит плохо. Что бы выглядело хорошо, нужно изначально всё правильно продумывать.

→ Ссылка