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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With