0

I am working on creating a checkbox that allows the user to view their password or not. I am using Material UI React for the UI components. I have the checkbox setup and working. The initial state of the input type is password and when the checkbox is clicked it changes to text, but once clicked again it does not revert back to password it stays on 'text' type no matter the state of checkState

// state
 const [checkState, setCheckState] = useState({
    checkedA: false,
    type: 'password',
  });
  
  // checkbox handle change function
  
  const handleChange = (event) => {
    console.log(checkState);
    setCheckState({ ...checkState, checkedA: event.target.checked, type: checkState ? 'text' : 'password' });
  
  }
  
  
  // textField Comp
              <TextField 
                  id="standard-basic" 
                  label="Password" 
                  type={checkState.type}
                  onChange={e => setData({...data, password: e.target.value})}
                  onKeyDown={(e)=> {keyDown(e)}}
                  />

1 Answer 1

3

checkState always appears to be a truthy value (it's an object). You want to change checkState.type based on its current value and not the checkState object's truthiness.

setCheckState({
  checkedA: event.target.checked,
  type: checkState.type === 'password' ? 'text' : 'password'
});
Sign up to request clarification or add additional context in comments.

2 Comments

oh you are right, that is a silly mistake on my part. Your solution works thank you!
Yep, doing it by the checkbox state is probably better in this case, though it will only update when changed anyway. Feel free to edit if you want, the idea is the same.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.