-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathuseCharLimit.js
39 lines (34 loc) · 998 Bytes
/
useCharLimit.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import { useState, useEffect, useCallback } from '@wordpress/element';
import { __, sprintf } from '@wordpress/i18n';
function useCharLimit( content = '', onChange, limit ) {
const [ charCount, setCharCount ] = useState( content?.length ?? 0 );
const [ errorMessage, setErrorMessage ] = useState( '' );
const handleContentChange = useCallback(
( value ) => {
setCharCount( value.length );
if ( value.length > limit ) {
setErrorMessage(
sprintf(
/* translators: %d: maximum number of character allowed */
__(
`Character limit exceeded. Please enter no more than %d characters.`,
'block-development-examples'
),
limit
)
);
} else {
setErrorMessage( '' );
onChange( value );
}
},
[ limit, onChange ]
);
useEffect( () => {
if ( content ) {
handleContentChange( content );
}
}, [ content, handleContentChange ] );
return { charCount, errorMessage, handleContentChange };
}
export default useCharLimit;