Search code examples
reactjsselectdefault

How can i define a default value for react-select v1


I had a react-select rendering a list of emails, and i need to keep the selected emails as a default option when the email is selected and saved, but the defaultValues are not working. How can i do that?

Here is my select component:

  const [selectedOption, setSelectedOption] = useState("")

  const makeEmailOption = item => ({
    value: item.id,
    label: item.ccEmail,
    id: item.id,
    chipLabel: item.ccEmail,
    rest: item,
    selected: item.selected
  })
  const makeEmailOptions = items => items.map(makeEmailOption)

  const handleChange = (value) => {
    setSelectedOption(value)
    props.emails(value)
  }

  return (
    <div>
      <Select
        multi={true}
        name={props.name}
        options={makeEmailOptions(props.ccemailfilter)} 
        onChange={handleChange}
        value={selectedOption} 
      />
    </div>
  )

I receive everything as props and work with that to make the options. How can i do that to make the default value if a field selected is true?


Solution

  • I came with the following solution, since my component use a function to set some variables to the select, i use a useEffect to call that with a filter right after the page render.

      useEffect(()  => {
         handleChange(makeEmailOption(props.ccemailfilter.filter(x => x.selected)))
      }, [])
    
      const handleChange = (value) => {
        setSelectedOption(value)
        props.emails(value)
      }
    

    So, the handleChange are called on the onChange of the select and once after the page loads, to create a value to the select to use.