javascript – Is there a way to change the type of an input in React?-ThrowExceptions

Exception or error:

So I’ve tried the following, I can’t seem to change the type of an input. So the same input can either be of type text or password but I can’t switch between both. This is a Semantic UI Input. (from semantic-ui-react)

   const [inputType, setInputType] = useState('password'||'text')

in my JSX:

   <Input type={inputType} value={inputValue} onChange={handleInput} className="landingInput" placeholder={inputPlaceholder} />

at initialization:

  setInputType('text'); 

after an event:

  setInputType('password'); // should update html template with type="password" but it doesn't

useEffect is used to make sure state is updated, every other hook works as expected. Could this be a security precaution? Can you think of a way to avoid creating a new input?

Thank you

How to solve:

Toggling input type is easy,
Here I used a button to toggle the input type to text and password.
check the working demo Here.

Check the updated code block

const App=()=>{
  const [inputType, setInputType] = useState('text');
  const inputPlaceholder = 'Add Here';
  const handleInput =()=>{}

  const toggleInput = ()=>{
setInputType(inputType === 'password' ? 'text': 'password')
  }
    return (
      <div>
        <input type={inputType} value="password" onChange={handleInput} className="landingInput" placeholder={inputPlaceholder} />
        <button onClick={toggleInput} >Toggle type</button>
      </div>
    );
}

Leave a Reply

Your email address will not be published. Required fields are marked *