Search code examples
reactjsreact-propsreact-selectreact-component

Using react-select ten times on same page and saving state separately for each Select


I am using React-select ten times on the same page due to a condition.

The condition is: First a day will be selected and the user will select values for that day. I will use bootstrap carousel and the user will select again any day and select his values. I am using react-select for same values on all days but, now I need separate values for each day. How to do this? Is bootstrap carousel right choice for this? I need help. Thank you.

Its a medical app and dr will click on Monday and he will be shown timing and he will select his timing for Monday. Let's say, then he clicks on Wednesday and selects separate timing for Wednesday. I will store these values in an array and show to the patient.

class DoctorSelectDay extends Component {
state = { 
       options: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'].map(obj => {
       return {value: `${obj}`, label: `${obj}`}
    }),
optionValues: [
  { value: 'chocolate', label: 'Chocolate' },
  { value: 'strawberry', label: 'Strawberry' },
  { value: 'vanilla', label: 'Vanilla' }
],
      open_id: [],
  };

changeHandler = e => {
    this.setState({ open_id: e ? e.map(x => x.value) : [] });
    console.log(this.state.open_id)
  };

render() {
    return (
          <div>
          <Select
            isMulti
            name="open_id"
            value={this.state.options.filter(item => this.state.open_id.includes(item.value))}
            onChange={this.changeHandler}
            options={this.state.options}
            className='select'
          /> 
          <button onClick={() =>{this.saveState()}} className='button-left'>Select Days</button>
          </div>
          )
    }
  }
export default DoctorSelectDay;
 

Solution

  • I think you should not use an array for saving your data. You are trying to get timing data for each day, this is a classic use case for a key value pair e.g {MON:'13:00-13:30'....} so I think you can use 2 select elements one for day value and one for the timing values (hope that I understood you, but the principles are same) when user select day you will set the state for day value setState({currentlySelectedDay:dayValue}) Then the user will select timing and you will save the state setState({daysTiming[this.state.currentlySelectedDay]=timingValue}) The indication for hiding / showing the elements is rhe value of currentlySelectedDay if empty show days if not show timing. In addition you should clear the day value while saving the timing. Hope that will work for you.