0

I have created a codesandbox for the issue (https://codesandbox.io/s/practical-flower-k6cyl?file=/src/App.tsx)

How can we make the "AGE" text (first option) in select box not to be selected again? It should only be displayed when the component renders.

Is there a better way to do this as default option i.e. is string whereas the others are numbers?

Any help is appreciated. Thanks

newbie
  • 530
  • 1
  • 9
  • 36
  • Check this question, I think the first answer may solve your problem: https://stackoverflow.com/a/68798605/3070545 – Iván Sep 08 '21 at 22:35

1 Answers1

0

You can add defaultValue to SelectBox and add disabled to first option.

<SelectBox
  defaultValue="myAgeLabel"
  id="age"
  value={selectedAge}
  onChange={changeAge}
>
  <option value="myAgeLabel" disabled>
    AGE
  </option>
  {AGES.map((age) => (
    <option key={age}>{age}</option>
  ))}
</SelectBox>

Answer inspired by these answers and adopted to react.

Ilya Ivanov
  • 23,148
  • 4
  • 64
  • 90
  • It gives me this error, when I use it in my code: `Warning: Select elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled select element and remove one of these props.` – newbie Sep 08 '21 at 23:09
  • @newbie Here is the link to a codesanbox I've used https://codesandbox.io/s/affectionate-roman-7hx81?file=/src/App.tsx . Gives me no warning and no errors. Your warning indicates of improper usage for `value` or `onChange`. Can you share your full code with this warning? – Ilya Ivanov Sep 09 '21 at 07:01
  • It doesn't give any error in codesandbox but in actual React app it does. The code is exactly the same as I copied it from the app to the codesandbox. Nothing is missing. The error is because you are using both `value` and `defaultValue` – newbie Sep 09 '21 at 09:17
  • Value is undefined by default. Are you sure you have `useState();` ? I've just checked this behavior locally for react 17.0.2 and still had no errors\warnings. Can you please copy your full code and create a github gist please? – Ilya Ivanov Sep 12 '21 at 07:38
  • It gives me this warning if I have some initial value for selectedAge, like so `useState(1);`. But again, selectedAge is undefined by default. – Ilya Ivanov Sep 12 '21 at 07:39