Reputation: 10116
In a React functional component the data is stored in a local state
const [member, setMember] = React.useState<Member>();
and the TextField value is mapped to the state value
<Grid container item lg={12}>
<TextField
label="First Name"
value={member?.firstName}
required
/>
</Grid>
However, when the member state is assigned a value the TextField refreshes but does not position the label above the value
When the TextField receives focus the label is positioned correctly. Changing the elements to the base InputLabel and Input elements has the same behavior.
<Grid container item lg={12}>
<FormControl>
<InputLabel htmlFor="component-simple">First Name</InputLabel>
<Input id="component-simple" value={member?.firstName} />
</FormControl>
</Grid>
What might be causing this behavior?
Upvotes: 1
Views: 968
Reputation: 10116
Turns out the problem was related to how React controlled components work. In order to be controlled the state variable containing the data, in this case "member" must be initialized with data or React does not consider the component "controlled".
The Member class was changed to initialize to an instance with no data, e.g., blank first name etc. Then the state value was initialized like this
const [member, setMember] = React.useState<Member>(new Member());
which caused the TextField to be controlled and the label displayed correctly, both when for a new member (the empty class instance) or an existing member instance which contained data.
Upvotes: 2