matieva
matieva

Reputation: 385

Problem with Select mui and Object value dissapears

I feel like I am very close to fixing it but when I change select option the selected values disappear. How can I avoid this when using Objects in MUI select? Code Sandbokx: https://codesandbox.io/s/jovial-pascal-ngpgyh?file=/src/App.js:0-909

import { useState } from "react";
import "./styles.css";
import { TextField, MenuItem } from "@material-ui/core";

export default function App() {
  const mainOptions = [
    { id: 1, text: "hello" },
    { id: 2, text: "This is just a test" }
  ];
  function handleFilterChange(e) {
    console.log(e.target);

    setChosenFilterId(e.target.value);
  }
  const [chosenFilterId, setChosenFilterId] = useState(0);
  return (
    <>
      <TextField
        select
        label="Category"
        value={mainOptions[chosenFilterId].text}
        onChange={(e) => handleFilterChange(e)}
      >
        {mainOptions.map((option, index) => {
          return (
            //When i try to change value={option} to value={index} I also get another error
            <MenuItem value={option} key={index}>
              {option.text}
            </MenuItem>
          );
        })}
      </TextField>
    </>
  );

Upvotes: 2

Views: 532

Answers (1)

Amr Eraky
Amr Eraky

Reputation: 1761

TextField's value and MenuItem's value couldn't be an Object, and both should be the same kay.

So,

<TextField
    select
    label="Category"
    value={chosenFilterId}                            // <= here
    onChange={(e) => handleFilterChange(e)}
>
    {mainOptions.map((option, index) => {
        return (
            <MenuItem value={option.id} key={index}>  {/*  <= here */ }
              {option.text}
            </MenuItem>
        );
    })}
</TextField>

Demo: https://codesandbox.io/s/immutable-star-ppzgzl?file=/src/App.js

Upvotes: 2

Related Questions