How to disable a select field in React

Last updated on Sep 7, 2022 by Suraj Sharma



In this tutorial, you will learn how you can disable a select field in React using a local state.


The select elements in JSX have a disabled property which accepts a truthy value, if disabled is set to true the select field gets disabled and the dropdown will not expand.


Here's a simple example to disable a select field in React using a local state.


Example


  import React from 'react';

  export function App(props) {
    const [isDisabled, setIsDisabled] = React.useState(false);

    const handleClick = () => {
      setIsDisabled(!isDisabled)
    }
    
    return (
      <div className='App'>
        <select defaultValue="" disabled={isDisabled}>
          <option value="">choose an option</option>
          <option value="one">1</option>
          <option value="two">2</option>
          <option value="three">3</option>
          <option value="four">4</option>
        </select>

        <button onClick={handleClick}>Click Me</button>
      </div>
    );
  }


Similary, we can even disable a select's option inside the dropdown.


  import React from 'react';

  export function App(props) {
    
    return (
      <div className='App'>
        <select defaultValue="">
          <option value="">choose an option</option>
          <option value="one">1</option>
          <option value="two" disabled={true}>2</option>
          <option value="three">3</option>
          <option value="four">4</option>
        </select>
      </div>
    );
  }


Related Solutions


Rate this post


Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.