'Pass default value to useState in React
I am having a form that passes values to a useState
I have this showrefid its value is set to either true or false
I want to pass the value of inputs into setAllValues based on true or false of showrefid
if showrefid is false I want to pass a default value that is already prefixed as value sony
{showrefid ? (
<input
name="userid"
onChange={handleChange}
style={styles.input}
type="text"
placeholder="userid"
/>
) : (
<input
name="userid"
value="sony"
onChange={handleChange}
type="text"
readonly="readonly"
/>
)}
const handleChange = (e) => {
setAllValues({ ...allValues, [e.target.name]: e.target.value });
};
Solution 1:[1]
You can set a default value to useState whenever the component gets rendered for the first time
const [allValues, setAllValues] = useState(showrefid ? { userid: "sony" } : {})
After that, you can set it directly to the input field
<input
name="userid"
value={allValues.userid}
onChange={handleChange}
type="text"
readonly="readonly"
/>
If showrefid can be modified from other places and you want to update your state accordingly, you can call useEffect
useEffect(() => {
if(!showrefid) {
setAllValues({ ...allValues, userid: "sony" })
}
}, [showrefid])
Solution 2:[2]
maybe consider using showrefid variable inside your handleChange function?
const handleChange = (e) => {
setAllValues(showrefid
? { ...allValues, [e.target.name]: e.target.value }
: { /* whatever value you want to set when false */ });
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Nick Vu |
| Solution 2 | Kayee |
