简体   繁体   中英

React defaultValue and value together in input fields

Since my form big,here i am pasting small part of code to understand better.

when i select username from select field then next disabled field dob must populate.So it works fine.

But problem is in my form i have a option called partial save button which will save in local storage .But this wont populate to dob field when we refresh page.

To fix this i changed value property to defaultValue then it will populate data but fails to set value when onchange select triggers.

Even i tried both defaultValue and value property together then i get error saying

index.js:1 Warning: MuiOutlinedInputInput contains an input of type text with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components

<FormControl >
        <InputLabel id="userLabel" >Username</InputLabel>
        <Select
          labelId="userLabel"
          id="userLabelId"

          MenuProps={MenuProps}
          label="Username"
          name="userName"
          onChange={(e) => {
            handleChange(e);
          }}
          value={userDetail.userName ?? ''}

        >
          <MenuItem value="">
            <em>None</em>
          </MenuItem>
          {userList ? userList.map((user) => (
            <MenuItem key={user.id} value={user.id ?? ''}>
              {user.userName}
            </MenuItem>
          )) : null}
        </Select>

      </FormControl>

      <TextField
        margin="normal"
        required
        id="dob"
        label="Date Of birth"
        name="dob"

        value={userDetail.dob ?? ''}

        disabled
      />

So, here's what is happening. When you say userDetail.dob?? '' userDetail.dob?? '' and userDetails.dob == null then you are telling this component "Please maintain your own state".

So the component says "no problem, I'll be an uncontrolled component".

Then you say to the component later, that is when userDetails != null , "I'm supplying you a value" & the component says "wait a minute, I'm an uncontrolled component, you can't make me into a controlled component".

So, start off by keeping it controlled by supplying it an empty string.

The value of Select and the value of menuitem must match. So you have to use userName.

{userList ? userList.map((flock) => (
  <MenuItem key={flock.id} value={flock.userName ?? ''}>
    {flock.userName}
  </MenuItem>
)) : null}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM