renathy
renathy

Reputation: 5355

React.JS FormControl: how to set properly default value

I have the following Control written for ReactJs app. The app and the code is not written by me, but I have to modify it. However, I am new to ReactJs.

function FormSelectNative({ name, label = null, defaultValue = '', options, valueKey = 'value', labelKey = 'label', ...props }) {

  return (
    <FormControl variant="outlined" size="small" fullWidth>
      <InputLabel id={name}>
        {label || name}
      </InputLabel>
      <Select
        name={name}
        labelId={name}
        label={label || name}
        defaultValue={defaultValue}
        {...props}
      >
        {options.map(option =>
          <MenuItem key={option[valueKey]} value={option[valueKey]}>{option[labelKey]}</MenuItem>
        )}
      </Select>
    </FormControl>
  );
}

I need to pass defaultValue parameter correctly.

I am trying to set it like this:

         <FormSelectNative
            options={games}
            valueKey="id"
            labelKey="name"
            onChange={handleGameSelect}
            defaultValue={games[0]} 
          />

But it doesn't work (default value is not set). I need to set default value to be first element of "games". However, here I believe is some mismatch of types, so it is not set.

Games element example:

{id: 1, name: "Name of Game", description: "Some test description", helper: "test.png", created_at: "2021-08-24T16:06:13", ... some other properties}

Upvotes: 1

Views: 360

Answers (1)

dglozano
dglozano

Reputation: 6607

The defaultValue has to be one of the possible value that you pass to the MenuItem. Each of those values is the game.id of each game, not the game object as a whole (a number, not an object). That's because you are doing value={option[valueKey]} where valueKey is id.

Therefore this is what you should do instead to set the default value correctly:

 <FormSelectNative
            options={games}
            valueKey="id"
            labelKey="name"
            onChange={handleGameSelect}
            defaultValue={games[0].id} // <<<--- get the id of the first item
          />

Upvotes: 1

Related Questions