Skip to content

Commit

Permalink
feat(PasswordInput): sync input type prop and state
Browse files Browse the repository at this point in the history
  • Loading branch information
emyarod committed Apr 22, 2021
1 parent 9d108ee commit 6e08ebd
Showing 1 changed file with 23 additions and 4 deletions.
27 changes: 23 additions & 4 deletions packages/react/src/components/TextInput/PasswordInput.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useContext, useState } from 'react';
import React, { useContext, useEffect, useState } from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
import { settings } from 'carbon-components';
Expand Down Expand Up @@ -30,18 +30,22 @@ const PasswordInput = React.forwardRef(function PasswordInput(
light,
tooltipPosition = 'bottom',
tooltipAlignment = 'center',
type = 'password',
hidePasswordLabel = 'Hide password',
showPasswordLabel = 'Show password',
size,
onTogglePasswordVisibility,
warn,
warnText,
...other
},
ref
) {
const [inputType, setInputType] = useState('password');
const togglePasswordVisibility = () =>
const [inputType, setInputType] = useState(type);
const handleTogglePasswordVisibility = (event) => {
setInputType(inputType === 'password' ? 'text' : 'password');
onTogglePasswordVisibility && onTogglePasswordVisibility(event);
};
const errorId = id + '-error-msg';
const warnId = id + '-warn-msg';
const textInputClasses = classNames(
Expand Down Expand Up @@ -159,7 +163,7 @@ const PasswordInput = React.forwardRef(function PasswordInput(
type="button"
className={passwordVisibilityToggleClasses}
disabled={disabled}
onClick={togglePasswordVisibility}>
onClick={handleTogglePasswordVisibility}>
{!disabled && (
<span className={`${prefix}--assistive-text`}>
{passwordIsVisible ? hidePasswordLabel : showPasswordLabel}
Expand All @@ -175,6 +179,10 @@ const PasswordInput = React.forwardRef(function PasswordInput(

const { isFluid } = useContext(FormContext);

useEffect(() => {
setInputType(type);
}, [type]);

return (
<div className={inputWrapperClasses}>
{!inline ? (
Expand Down Expand Up @@ -282,6 +290,12 @@ PasswordInput.propTypes = {
*/
onClick: PropTypes.func,

/**
* Callback function that is called whenever the toggle password visibility
* button is clicked
*/
onTogglePasswordVisibility: PropTypes.func,

/**
* Specify the placeholder attribute for the `<input>`
*/
Expand Down Expand Up @@ -309,6 +323,11 @@ PasswordInput.propTypes = {
*/
tooltipPosition: PropTypes.oneOf(['top', 'right', 'bottom', 'left']),

/**
* The input type, either password or text
*/
type: PropTypes.oneOf(['password', 'text']),

/**
* Provide the current value of the `<input>`
*/
Expand Down

0 comments on commit 6e08ebd

Please sign in to comment.