Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react password eye icon for multiple fields

Tags:

reactjs

I have three password fields, each one has a eye icon to let consumer show/hide password,

I am trying with the below code but if i click hide/show for one field then it is effecting to other fields too.

Please guide me with any example of correct the below code

class ShowPassword extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      type: 'input',
      score: 'null'
    }
    this.showHide = this.showHide.bind(this);
  }

  showHide(e){
    //e.preventDefault();
    //e.stopPropagation();
    this.setState({
      type: this.state.type === 'input' ? 'password' : 'input'
    })  
  }


  render(){
    return(
      <div>
      <label className="password">Current Password
      <input type={this.state.type} className="password__input"/>
      <span className="password__show" onClick={this.showHide}>{this.state.type === 'input' ? 'Hide' : 'Show'}</span>
      </label>

            <label className="password">New Password
      <input type={this.state.type} className="password__input"/>
      <span className="password__show" onClick={this.showHide}>{this.state.type === 'input' ? 'Hide' : 'Show'}</span>
      </label>

            <label className="password">Confirm Password
      <input type={this.state.type} className="password__input"/>
      <span className="password__show" onClick={this.showHide}>{this.state.type === 'input' ? 'Hide' : 'Show'}</span>
      </label>
        </div>
    )
  }
}

ReactDOM.render(<ShowPassword/>, document.getElementById('react'));

Below is the jsbin link to play with

https://jsbin.com/homuxoq/edit?html,css,js,output

like image 306
user804401 Avatar asked Oct 17 '22 08:10

user804401


1 Answers

Extract your input field into it's own component

class PasswordField extends React.Component{
  state = {
    type: 'text',
  }


  handleClick = () => this.setState(({type}) => ({
    type: type === 'text' ? 'password' : 'text'
  }))


  render() {
    const { label } = this.props

    return (
      <label className="password">{label}
        <input type={this.state.type} className="password__input"/>
        <span className="password__show" onClick={this.handleClick}>{this.state.type === 'text' ? 'Hide' : 'Show'}</span>
      </label>
    )
  }
}

Link to JSBin

Another thing I'd like to mention here, is that there is no input type of input. Therefore I've replaced it with the valid value text.

like image 51
dschu Avatar answered Nov 15 '22 06:11

dschu