Skip to content

Commit 15e009e

Browse files
committed
Revert "simplify state mgmt in Input even more"
This reverts commit aa9b253.
1 parent 77018ae commit 15e009e

File tree

1 file changed

+9
-10
lines changed

1 file changed

+9
-10
lines changed

app/javascript/src/components/Input.jsx

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import React, { useState } from "react";
1+
import React, { useState, useEffect } from "react";
22

33
export 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)

0 commit comments

Comments
 (0)