B
B
blew_sweet2021-06-24 15:41:21
JavaScript
blew_sweet, 2021-06-24 15:41:21

How to make React-select's "Reset All" button work?

I decided to use the react-select library, the task is as follows, there is a calculator, where there are several select. And I can’t set up the “Reset All” button in any way so that all values ​​\u200b\u200bare reset. I found an example, for one select, but when there are a lot of them, it is not relevant to prescribe unique values ​​for each

handleChange should process changes, and handleClick should be set to zero, change It seems to work fine, but nothing happens when you click, although if you look in the console, the object itself is reset

export const Calculator = () =>{
  const options = [
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'vanilla', label: 'Vanilla' },
  ];

  const [value,setValue] = useState({})

  const flags = [
    {id: 'first', text:'Включить цену за проживание'},
    {id: 'second', text:'Варианты со скидкой'}
  ]

  const handleChange = (val,actionMeta) => {
    setValue({
      ...value,
      [actionMeta]: val
    })
  }
  const handleClick = () => setValue({})

  return (
    <aside className={classes.calculator}>
      <h4 className={classes.title}>
        Что хотите найти?
      </h4>
      <form onSubmit={(e)=>{
        e.preventDefault()
      }} className={classes.form}>
        <div className={classes.fields}>
          <div className={classes.field}>
            <div className={classes.subtitle}>Язык</div>
            <CustomSelect propValue={value} options={options} onChange={handleChange} name={'string'} id={1}  placeholder={'На каком языке?'} styles={customStyles}/>
            {JSON.stringify(value)}
          </div>
          <div className={classes.field}>
            <div className={classes.subtitle}>Страна</div>
            <CustomSelect  propValue={value['2'] } onChange={handleChange} name={'2'} id={2} placeholder={'На каком языке?'} styles={customStyles}/>
          </div>
          <div className={classes.field}>
            <div className={classes.subtitle}>Город</div>
            <CustomSelect  propValue={value['3'] } onChange={handleChange} name={'3'} id={3} placeholder={'Какой город?'} styles={customStyles}/>
          </div>
          <div className={classes.field}>
            <div className={classes.subtitle}>Возрастная группа</div>
            <CustomSelect propValue={value['4']} onChange={handleChange} name={'4'} id={4} placeholder={'Какой возраст?'} styles={customStyles}/>
          </div>
          <div className={classes.field}>
            <div className={classes.subtitle}>Продолжительность обучения</div>
            <CustomSelect  propValue={value['5']} onChange={handleChange} name={'5'} id={5} placeholder={'Долго?'} styles={customStyles}/>
          </div>
          <div className={classes.field}>
            <div className={classes.subtitle}>Количество учеников в классе</div>
            <CustomSelect  propValue={value['sum']} onChange={handleChange} name={'sum'}  id={6} placeholder={'Кол-во учеников?'} styles={customStyles}/>
          </div>
        </div>
        <div className={classes.feePerWeek}>
          <div className={classes.feePerWeek}>
            <div className={cn(classes.subtitle, classes.subtitleBigMargin )}>
              Стоимость обучения за неделю
            </div>
            <MultiRangeSlider min={0} max={1000}/>
          </div>
        </div>
        <div className={classes.flags}>
          <Checkbox id={flags[0].id} text={flags[0].text}/>
          <Checkbox id={flags[1].id} text={flags[1].text}/>
        </div>
        <CalculatorParameters onChange={handleChange} customStyles={customStyles} fieldValue={value}/>
        <div className={classes.buttons}>
          <button type={'submit'} className={classes.submit}>Применить</button>
          <button className={classes.resetButton} onClick={handleClick}>Сбросить все</button>
        </div>
      </form>
    </aside>

  )
}

CustomSelect component
export const CustomSelect = ({placeholder,id,propValue,onChange, options, styles,name}) =>{
  const initialOptions = [
    { value: 'chocolate', label: 'Chocolate' },
    { value: 'strawberry', label: 'Strawberry' },
    { value: 'vanilla', label: 'Vanilla' },
    { value: 'vanilla', label: 'Vanilla' },
    { value: 'vanilla', label: 'Vanilla' },
    { value: 'vanilla', label: 'Vanilla' },
    { value: 'vanilla', label: 'Vanilla' },
    { value: 'vanilla', label: 'Vanilla' },
    { value: 'vanilla', label: 'Vanilla' },
    { value: 'vanilla', label: 'Vanilla' },
  ];
  const [value,setValue] = useState(propValue)
  useEffect(()=>{
    setValue(propValue)
  }, [propValue])

  const handleOnChange = ({value}) => {
    if (typeof onChange ==='undefined') {
      return null
    } else {
      onChange(value, name)
    }
  }
  return (
    <Select onChange={handleOnChange} name={name} value={value} instanceId={id} placeholder={<span>{placeholder}</span>}  styles={styles || customStyles} options={options ?? initialOptions} />
  )
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
ParaBellum577, 2021-06-24
@ParaBellum577

I don’t see handleClick being called at all, propValue is undefined, you don’t pass it to the component. I advise you to output to the console the props that you pass to the components, then it will be clearly clear where there are errors.

0
0xD34F, 2021-06-24
@0xD34F

Select takes an object, an array of objects, or null as value, and you try to slip a string into it (the value property of the options array element). Store objects as selected values ​​(no need to destructure the parameter in handleOnChange, pass it in its entirety to onChange); or inside CustomSelect, search for the desired option by its value and pass the found (or null if the search did not return results) to Select instead of the string value received from the parent component.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question