1

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?

2 Answers2

1

You almost have it, but in this case, you are setting the value to the selectedOption instead of setting the defaultValue. Also, you are changing the default value each time there is a change, which shouldn't be needed.

const defaultVal = {value: selectedOption, label: selectedOption};

return (
  <div>
    <Select
      multi={true}
      name={props.name}
      options={makeEmailOptions(props.ccemailfilter)} 
      defaultValue={defaultVal} 
    />
  </div>
)
brandonwang
  • 1,603
  • 10
  • 17
  • Didn't work, i get cant even select the options when i use that. Dont know where to go from here – Altair Todescatto F Jul 10 '19 at 18:59
  • Do you have a reproducible example? Can you upload it to an online sandbox? – brandonwang Jul 10 '19 at 19:04
  • I dont think that i can do that, the select is rendered in a file, that is being rendered from another file. The code i put in the question is the final select that receives all the info from other files and set on the select itself. – Altair Todescatto F Jul 10 '19 at 19:15
  • I forgot that you needed to specify a value and a label; you can't just pass in the value like i had it before. Try this answer – brandonwang Jul 10 '19 at 20:38
  • 1
    Your answer is not wrong, but didn't work on my case for a reason i dont understand. I answer my question with the solution i came up with.Thank you anyway – Altair Todescatto F Jul 12 '19 at 17:02
0

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.