File tree Expand file tree Collapse file tree 1 file changed +9
-10
lines changed
app/javascript/src/components Expand file tree Collapse file tree 1 file changed +9
-10
lines changed Original file line number Diff line number Diff line change 1- import React , { useState } from "react" ;
1+ import React , { useState , useEffect } from "react" ;
22
33export default Input = ( {
44 label,
@@ -15,18 +15,17 @@ export default Input = ({
1515 tooltip,
1616 ...props
1717} ) => {
18- // if we don't have an onChange handler, this component is an uncontrolled component
19- // if we have an onChange handler, we'll manage state like a traditional controlled component
20- let value , setValue ;
21- if ( ! onChange ) {
22- value = initialValue
23- } else {
24- ( [ value , setValue ] = useState ( initialValue || "" ) )
25- }
26-
18+ const [ value , setValue ] = useState ( initialValue || "" )
2719 const labelClassNames = `${ required ? 'required' : '' } ${ labelClassName || '' } `
2820 const inputClassNames = `form-control ${ className || '' } ${ labelClassNames . includes ( 'sr-only' ) ? 'mt-6' : '' } `
2921
22+ // if we have an onChange handler, we'll manage state like a traditional controlled component (and don't need the useEffect)
23+ // if we don't have an onChange handler, this component behaves more like an uncontrolled component
24+ // the useEffect lets us always get the value from the prop
25+ if ( ! onChange ) {
26+ useEffect ( ( ) => setValue ( initialValue ) , [ initialValue ] ) ;
27+ }
28+
3029 const handleChange = ( e ) => {
3130 setValue ( e . target . value )
3231 onChange ?. ( e )
You can’t perform that action at this time.
0 commit comments