How to change input type in React Js

Last updated : Jul 30, 2023 12:00 AM

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>
  </>
 )
}
Figure 1:
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>
      </>
 )
}
Figure 2: React select to multiple select
Figure 2: React select to multiple select
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...