LTM
LTM

Reputation: 63

How to show input field when clicking on other in select-react

I'm using react-select in nextJS. I need to create an input field when a user clicks on "other" option and take what the user fills.

 <SelectComponent
        name={'types'}
        closeMenuOnSelect
        options={[
          { value: 'big', label: 'big' },
          { value: 'small', label: 'small' },
          { value: 'other', label: 'Other' },
        ]}
 />

How can this be achieved? Thanks.

Upvotes: 1

Views: 1092

Answers (1)

illia chill
illia chill

Reputation: 2056

A.You define your variable to show/hide your input

const [showInput, setShowInput] = useState(false);

B. You create your input component, and define hidden or display:none style according to the variable value

<input type="text" name="name" style={{display: showInput ? "block": "none"}} />

C. You define the behaviour with onChange of your SelectComponent, something like this

onChange={(selected) => {
  //you debug `selected` variable to see values you need etc.
  console.log(selected)
  //you writes if condition here, it's an example of code below
  if (selected == 'other'){
  //showing input
  setShowInput(true)
  }
  else{
  //need set to false if not "others", because user can change select a lot of times
  setShowInput(false)
  }
}}

I don't know what are you using as , but when you save your data from the <form>, you need always to check your select and save data from input only if "other" option was selected.

Upvotes: 1

Related Questions