How to change input type in React Js

Last updated : August 27, 2022

In React Js, I can use a state variable to change the input type of an input element. I just use a state variable to hold the input type like <input type={inputType} />. When I assign a valid input type to the inputType state variable, the input element will change to that type.

Here is an example of assigning different input types to an input element.

import { useState } from "react"

export const ChangeInputType = () =>{
  const [inputType, setInputType] = useState<string>("")
  const [inputTypeIndex, setInputTypeIndex] = useState<number>(0)
  const inputTypes = ["text", "radio", "checkbox", "hidden", "password"]

  const changeInputType = (inputIndex: number) => {
    setInputType(inputTypes[inputIndex])
    setNextInputIndex()
  }
  const setNextInputIndex = () => {
    setInputTypeIndex((prev) => {
      if(prev === inputTypes.length-1){
        return 0
      }
      return prev+1
    })
  }
 return(
  <>
  <div>{inputType}</div>
  <div><input type={inputType} /></div>
  <div><button onClick={() => changeInputType(inputTypeIndex)}>Update</button></div>
  </>
 )
}
Change input type in React
Figure 1:

The function setNextInputIndex() is to update the index to show the next input type.

How to toggle between select and multiple select?

I can use the multiple property of the select element to toggle between select and multiple select elements.

import { useState } from "react"

export const ChangeInputType = () =>{
 
  const [isMultiple, setIsMultiple] = useState<boolean>(false)
  
  const changeInputType = () => {
    setIsMultiple(prev => !prev)
  }
  
 return(
  <>
  <div>Is multiple Select : {isMultiple}</div>
  <div>
       <select multiple={isMultiple}>
          <option>Select</option>
          <option>Option 1</option>
          <option>Option 2</option>
          <option>Option 3</option>
       </select>
  </div>
  <div><button onClick={changeInputType}>Update</button></div>
  </>
 )
}
React select to multiple select
Figure 2: React select to multiple select
L Raney
By: L Raney
Lance is a software engineer with over 15 years of experience in full-stack software development.
Read more...

Comments are disabled

No Comments