@@ -56,7 +56,6 @@ import {
5656 connect ,
5757 decodeHtml ,
5858 extractModifierKeysFromFocusShortcuts ,
59- handleCaretPosition ,
6059 isEmpty ,
6160 parseFocusShortcuts ,
6261} from '../../utils' ;
@@ -75,6 +74,19 @@ const useConstructor = (callBack = () => {}) => {
7574 setHasBeenCalled ( true ) ;
7675} ;
7776
77+ /**
78+ * inputValue:
79+ * The value which is passed to the html input box.
80+ * The onChange handler(event listener on input box) should directly update inputValue.
81+ *
82+ * For uncontrolled components, we maintain the input value(useState - currentValue).
83+ * Hence, onChange should call setValue to update currentValue directly.
84+ *
85+ * For controlled components, we get the input value(props.value).
86+ * Hence, onChange should call props.onChange,
87+ * which then updates currentValue by calling setValue in useEffect.
88+ */
89+
7890const SearchBox = ( props ) => {
7991 const {
8092 selectedValue,
@@ -506,9 +518,6 @@ const SearchBox = (props) => {
506518 if ( value === undefined ) {
507519 setValue ( inputValue , false , props , undefined , true , false ) ;
508520 } else if ( onChange ) {
509- // handle caret position in controlled components
510- handleCaretPosition ( e ) ;
511-
512521 onChange (
513522 inputValue ,
514523 ( { isOpen } = { } ) => {
@@ -992,6 +1001,11 @@ const SearchBox = (props) => {
9921001 }
9931002 } , [ rawData , aggregationData , isLoading , error ] ) ;
9941003
1004+ /**
1005+ * For uncontrolled component,
1006+ * props.value would be changed directly,
1007+ * which then needs to update currentValue by calling setValue
1008+ */
9951009 useEffect ( ( ) => {
9961010 if ( hasMounted . current ) {
9971011 if (
@@ -1413,7 +1427,7 @@ const SearchBox = (props) => {
14131427 { ...getInputProps ( {
14141428 className : getClassName ( props . innerClass , 'input' ) ,
14151429 placeholder : props . placeholder ,
1416- value : currentValue === null ? '' : currentValue ,
1430+ value : Object . hasOwn ( props , 'value' ) ? props . value : currentValue || '' ,
14171431 onChange : onInputChange ,
14181432 onBlur : withTriggerQuery ( props . onBlur ) ,
14191433 onFocus : handleFocus ,
@@ -1473,7 +1487,7 @@ const SearchBox = (props) => {
14731487 aria-label = { props . componentId }
14741488 className = { getClassName ( props . innerClass , 'input' ) || null }
14751489 placeholder = { props . placeholder }
1476- value = { currentValue || '' }
1490+ value = { Object . hasOwn ( props , 'value' ) ? props . value : currentValue || '' }
14771491 onChange = { onInputChange }
14781492 onBlur = { withTriggerQuery ( props . onBlur ) }
14791493 onFocus = { withTriggerQuery ( props . onFocus ) }
0 commit comments