I have the following problem. The below code does not work as intended. The first log displays the correct value. e.g. "SomeName". But "SomeName" is not displayed in the inputName
text.
To make things more readable I simplified the function.
function EditAboutModal(props) {
const [show, setShow] = useState(false);
console.log(props.data.Name);
const [Name, setName] = useState(props.data.Name);
function handleNameChange(e) {
setName(e.target.value);
}
return (
<>
<div className="row mb-3">
<label htmlFor="inputName" className="col-sm-2 col-form-label">Name:</label>
<div className="col-sm-10">
<input type="text" className="form-control" id="inputName" value={Name} onChange={handleNameChange} />
</div>
</div>
</>
);
}
I expect the useState
to set the Name
variable to props.data.Name
.
The log correctly displays that a value exists for this variable, but no value is shown in the textfield and when I log the Name
variable it is shown as unknown.
2
Answers
It can be
null
or something else in the first component render. UseuseEffect
to handle this problem:I provide the simpler version of your code into the code snippet, as you can see as long as you passed the right props to the EditAboutModal it would work.
Just remember since you are seting the data.name as initial value in your state, if the data.name is changing in the props after first initialization it will not continuesly change the input value, since the initial value only set once.
If you want to continuesly miror the props.data.name changes, you need to add an useEffect and fource to do so(which is not advisable, look at this for more information) but if you want to do this no matter what, this is the way: