1- import React , { useState , useCallback , useEffect } from 'react' ;
1+ import React , { useState , useCallback } from 'react' ;
22import styled from 'styled-components' ;
33import css from '@styled-system/css' ;
44import { Stack , Input } from '../..' ;
@@ -42,26 +42,14 @@ export const Textarea: React.FC<ITextareaProps> = ({
4242 autosize,
4343 ...props
4444} ) => {
45- const [ wordCount , setWordCount ] = useState ( 0 ) ;
46- const [ value , setValue ] = useState ( '' ) ;
45+ const [ value , setValue ] = useState ( props . value || '' ) ;
4746
48- const updateValues = v => {
49- if ( maxLength ) {
50- const trimmedText = v . substring ( 0 , maxLength ) ;
51- setValue ( trimmedText ) ;
52- setWordCount ( trimmedText . length ) ;
53- } else {
54- setValue ( v ) ;
55- }
47+ const internalOnChange = ( event : React . ChangeEvent < HTMLTextAreaElement > ) => {
48+ if ( onChange ) onChange ( event ) ;
49+ setValue ( event . target . value ) ;
50+ if ( autosize ) resize ( event . target ) ;
5651 } ;
5752
58- useEffect ( ( ) => {
59- if ( props . value ) {
60- updateValues ( props . value ) ;
61- }
62- // eslint-disable-next-line
63- } , [ ] ) ;
64-
6553 const Wrapper = useCallback (
6654 ( { children } ) =>
6755 maxLength ? (
@@ -74,24 +62,6 @@ export const Textarea: React.FC<ITextareaProps> = ({
7462 [ maxLength ]
7563 ) ;
7664
77- // eslint-disable-next-line consistent-return
78- const update = ( e : React . ChangeEvent < HTMLTextAreaElement > ) => {
79- if ( onChange ) onChange ( e ) ;
80- updateValues ( e . target . value ) ;
81- if ( autosize ) resize ( e . target as HTMLTextAreaElement ) ;
82- } ;
83-
84- const keyPress = ( e : React . KeyboardEvent < HTMLTextAreaElement > ) => {
85- if ( onKeyPress ) onKeyPress ( e ) ;
86- if ( maxLength ) {
87- if ( maxLength <= wordCount ) {
88- return false ;
89- }
90- }
91-
92- return true ;
93- } ;
94-
9565 const resize = ( element : HTMLTextAreaElement ) => {
9666 const offset = 2 ; // for borders on both sides
9767 element . style . height = '' ; // reset before setting again
@@ -103,13 +73,13 @@ export const Textarea: React.FC<ITextareaProps> = ({
10373 < Wrapper >
10474 < TextareaComponent
10575 value = { value }
106- onChange = { update }
107- onKeyPress = { keyPress }
76+ onChange = { internalOnChange }
77+ maxLength = { maxLength }
10878 { ...props }
10979 />
11080 { maxLength ? (
111- < Count limit = { maxLength <= wordCount } >
112- { wordCount } /{ maxLength }
81+ < Count limit = { maxLength <= value . length } >
82+ { value . length } /{ maxLength }
11383 </ Count >
11484 ) : null }
11585 </ Wrapper >
0 commit comments