Skip to content

Commit

Permalink
fix(TextArea): adds character counter alert (#12411)
Browse files Browse the repository at this point in the history
* feat: add counter alert

* feat: visually hide alert

Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
  • Loading branch information
jnm2377 and kodiakhq[bot] authored Nov 1, 2022
1 parent 707f5b2 commit 856d528
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 1 deletion.
15 changes: 14 additions & 1 deletion packages/react/src/components/TextArea/TextArea.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import PropTypes from 'prop-types';
import React, { useState, useContext } from 'react';
import React, { useState, useContext, useEffect } from 'react';
import classNames from 'classnames';
import deprecate from '../../prop-types/deprecate';
import { WarningFilled } from '@carbon/icons-react';
Expand Down Expand Up @@ -40,6 +40,7 @@ const TextArea = React.forwardRef(function TextArea(
const [textCount, setTextCount] = useState(
defaultValue?.length || value?.length || 0
);
const [ariaAnnouncement, setAriaAnnouncement] = useState('');

const textareaProps = {
id,
Expand All @@ -61,6 +62,15 @@ const TextArea = React.forwardRef(function TextArea(
textareaProps.maxLength = maxCount;
}

useEffect(() => {
const lastTen = maxCount - 10;
if (textCount >= lastTen) {
setAriaAnnouncement(`${maxCount - textCount} characters left.`);
} else {
setAriaAnnouncement('');
}
}, [textCount, maxCount]);

const labelClasses = classNames(`${prefix}--label`, {
[`${prefix}--visually-hidden`]: hideLabel && !isFluid,
[`${prefix}--label--disabled`]: disabled,
Expand Down Expand Up @@ -139,6 +149,9 @@ const TextArea = React.forwardRef(function TextArea(
<WarningFilled className={`${prefix}--text-area__invalid-icon`} />
)}
{input}
<span className={`${prefix}--text-area__counter-alert`} role="alert">
{ariaAnnouncement}
</span>
{isFluid && <hr className={`${prefix}--text-area__divider`} />}
{isFluid && invalid ? error : null}
</div>
Expand Down
11 changes: 11 additions & 0 deletions packages/styles/scss/components/text-area/_text-area.scss
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,17 @@
fill: $support-error;
}

.#{$prefix}--text-area__counter-alert {
position: absolute;
overflow: hidden;
width: 1px;
height: 1px;
padding: 0;
border: 0;
margin: -1px;
clip: rect(0, 0, 0, 0);
}

//-----------------------------
// Disabled
//-----------------------------
Expand Down

0 comments on commit 856d528

Please sign in to comment.