Home > Net >  Select is not disabled when changing boolean value with useState React
Select is not disabled when changing boolean value with useState React

Time:11-25

I have a useState called isPackage which is a boolean that starts as false. I use this hook in a simple JSX select, which when isPackage is true requires it to be enabled but when it is false it is disabled. The problem starts from the rendering since although usPackage is false, the select is shown enabled. This is my code:

UseState:

const [isPackage, setIsPackage] = useState(false)

JSX:

 <select disabled = { isPackage ? true : false }>

I change the state of isPackage using this function:

const handlerPresentationSelected = () => {
  setIsPackage(!isPackage)
}

If I make the first change using the function above, it is executed correctly to pass isPackage to true, when I use the function again it correctly changes to false, however the select is always enabled.

CodePudding user response:

Per this answer, https://stackoverflow.com/a/8311341/12101554, you have to set disabled on the <option> tags, not the <select> tag.

const [isPackage, setIsPackage] = useState(false)

return (
  <div className="App">
    <button onClick={() => setIsPackage((cur) => !cur)}>toggle isPackage: {isPackage.toString()}</button>
    <br />
    <select>
      <option disabled={isPackage}>a</option>
      <option disabled={isPackage}>b</option>
    </select>
  </div>
);

If your options are in an array, then just set that property on the <select> in the .map

CodePudding user response:

Based on the description of the question:

when isPackage is true requires it to be enabled but when it is false it is disabled

It would seem to indicate that perhaps this line should be the other way around:

<select disabled = { isPackage ? true : false }>

In addition, it seems that a required property should also be set when isPackage is true. With this added, the logic could be put in this way:

// If isPackage is true, the select is required, and not disabled
// If isPackage is false, the select is not required, and is disabled

<select {...{[isPackage ? "required" : "disabled"]: true}}>

And to toggle isPackage based on previous value on the button:

<button onClick={() => setIsPackage((prev) => !prev)}>

Here is a quick example to visualize the changes:

(It can run in the snippets for convenience)

const App = () => {
  const [isPackage, setIsPackage] = React.useState(false);

  return (
    <div className="app">
      <h3>{`isPackage is: ${isPackage}`}</h3>
      <button onClick={() => setIsPackage((prev) => !prev)}>
        Toggle isPackage            
  • Related