Mui Select fails to update value when defaultValue is specified

I am using a select component from the MUI React library along with react-hook-form and controller. I have set a default value in the controller to use the reset function, but I am unable to change the value when a default value is set. Everything works as expected when there is no default value. Here is my code:

import * as React from "react";
import { useTheme } from "@mui/material/styles";
import OutlinedInput from "@mui/material/OutlinedInput";
import InputLabel from "@mui/material/InputLabel";
import MenuItem from "@mui/material/MenuItem";
import FormControl from "@mui/material/FormControl";
import Select from "@mui/material/Select";
import { useFormContext, Controller } from "react-hook-form";
import Box from '@mui/material/Box';
const ITEM_HEIGHT = 48;
const ITEM_PADDING_TOP = 8;
const MenuProps = {
  PaperProps: {
    style: {
      maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
      width: 250,
    },
  },
};

function getStyles(name, personName, theme) {
  return {
    fontWeight:
      personName.indexOf(name) === -1
        ? theme.typography.fontWeightRegular
        : theme.typography.fontWeightMedium,
  };
}

function MySelect({ formname, name, reset, setSelected, data = [] }) {
  const {
    control,
    formState: { errors },
    setValue,
  } = useFormContext();

  let isError = false;
  let errorMessage = "";
  if (errors && errors.hasOwnProperty(name)) {
    isError = true;
    errorMessage = errors[name].message;
  }

  const handleChange = (event) => {
    const {
      target: { value },
    } = event;
    setSelected(
      // On autofill we get a stringified value.
      typeof value === "string" ? value.split(",") : value
    );
  };


  return (
    <Box sx={{minWidth: 120}}>
      <InputLabel id="demo-multiple-name-label">{name}</InputLabel>
      <Controller
        name={formname}
        style={{ width: 200 }}
        control={control}
        defaultValue=""
        render={({ field: { onChange, value } }) => (
          <Select
            sx={{ width: 200 }}
            labelId="demo-multiple-name-label"
            id="demo-multiple-name"
            multiple={false}
            value={value}
            onChange={onChange}
            input={<OutlinedInput label={name} />}
            MenuProps={MenuProps}
            error={isError}
            helperText={errorMessage}
          >
            {data.map((element, i) => {
              if (element.bsa_maskenkey)
                return (
                  <MenuItem value={element} key={i}>
                    {`${element.bsa_maskenkey} ${element.we_menge}`}
                  </MenuItem>
                );
              else if (element.blager_maskenkey)
                return (
                  <MenuItem value={element} key={i}>
                    {`${element.blager_maskenkey} ${element.blagerpo_maskenkey} | Menge: ${element.summe}`}
                  </MenuItem>
                );
              else
                return (
                  <MenuItem value={element} key={i}>
                    {`${element.objekt} | Menge: ${element.menge}`}
                  </MenuItem>
                );
            })}
          </Select>
        )}
      />
    </Box>
  );
}
export default React.memo(MySelect)


Answer №1

It is important to choose between using controlled or uncontrolled input elements in your form - specify either the value prop or the defaultValue prop, but not both. Controlled inputs are typically preferred as they allow you to manage the input value within the form's state.

In order to set default values for your form fields using the useForm hook, you simply need to declare them in the defaultValues property. These values will then be automatically bound to the corresponding input fields in your form. For example:

useForm({
  mode: 'onSubmit',
  reValidateMode: 'onChange',
  defaultValues: { FieldA: "foo", FieldB: "xai" },
  shouldFocusError: true,
  shouldUnregister: false,
  shouldUseNativeValidation: false
})

By following this approach, the default values for FieldA and FieldB will be set as initial values in their respective form fields. Just ensure that you correctly bind these fields with the form's state to maintain synchronization.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the recommended data type for Material UI Icons when being passed as props?

What specific type should I use when passing Material UI Icons as props to a component? import {OverridableComponent} from "@mui/material/OverridableComponent"; import {SvgIconTypeMap} from "@mui/material"; interface IconButtonProps { ...

Error caused by touch in JSX email field

There is a minor bug that doesn't impact the functionality, but it's present and bothersome. Within my react.js application, I have a signup form. Below is a simplified version: import { useState } from "react" import {signupApi} from ...

Exploring the Fusion of Material UI Searchbox and Autocomplete in React

Looking for help with my AppBar component from Material UI. I want the Searchbox field to function similarly to what is seen on https://material-ui.com/. It should appear as a Searchbox but display selectable options like Autocomplete after entering input. ...

ReactJS and Redux: Attempting to update the state of a React component that is unmounted is not possible

Check out this .gif recording showcasing the issue: After logging in, upon the initial load of my Dashboard component, an error is displayed in the console. Warning: Can't perform a React state update on an unmounted component. This is a no-op, but ...

"Utilize React to dynamically render Material UI icons in a web application

Hey there, I could use some help with a certain issue. In my project, I'm utilizing Material UI icons and they are set up in a way where I have to import them like this: import {Muicon } from '@/lib/material'; ... <Muicon.Visibility /& ...

Load a React component in the same spot when clicked

Is there a way to implement a functionality where clicking on different buttons in a panel will display different components in the same location? <AddNotification /> <EditNotification /> <DeleteNotification /> const AdminPanel = () =& ...

Tips for incorporating hooks into the onError handler in react-query

In our development process, we have opted for the combination of Next.js and react-query in all aspects. Our goal is to establish a global query system that can automatically refresh an access token and re-execute a query when it encounters failure due to ...

What is preventing the document title from updating in Google Analytics on React?

My process for initializing Google Tag Manager involved incorporating the following code snippet. import TagManager from 'react-gtm-module'; const tagManagerArgs = { gtmId: 'GTM-TLDWCL3' } TagManager.initialize(tagManagerArgs); To ...

What is the best way to display JSON data in a readable format?

I received a JSON file with the following structure: { "data":{ "uuid":"123", "name":"TestData", "alias":null, "created_at":"2021-03-17T11:57:29.000000Z&q ...

Is there a way to assign multiple paths to a single page within the NextJS pages directory?

I'm currently working on a project that has two different themes, and I have the ability to switch between them based on the environment. Everything works perfectly, but I'm encountering an issue with paths. Some pages should open with different ...

Having trouble establishing a connection to the SQL Server database in my React application

I'm stuck trying to connect my database with my React app. I created the database using SQL in SQL Server Management Studio. I attempted to use express for the connection, but it seems like there are pieces missing in my code. Can someone guide me on ...

When using framer-motion with Next.js, it will smoothly animate from 0vh to 100vh, but it struggles to animate from -100vh to 0vh

I have been working on animating a navbar to open and close, but I'm encountering an issue. I have a larger container that changes height during the animation, and I want to simultaneously slide down an inner container as it adjusts its height. The pr ...

The variable 'React' has been declared but appears to be unused, what might be causing this problem?

Currently, I am developing a contact application using Python with React. While utilizing Vite and Flask for development, I encountered an error stating that 'React' is defined but never used. Below is a snippet of my code structure: This sectio ...

Differences between NextJS default server-side rendering and implementing a custom server

What are the benefits of using Express (or another server) when implementing SSR with Next.js instead of simply using the built-in next start command for initialization? ...

Dynamic Selection of JSON Key-Value Pairs in React Framework

My json data structure resembles the following: { "index": 1, "ln": "27953", "name": "Product 1", "availability": { "day0726": "G", "day0727": "G", "day0728": "G", } } I am looking for a way to dynamically disp ...

Issues arise when implementing ReactJS transitions for progress bars

As a newcomer to the world of ReactJS, I have been exploring the FB documentations and online tutorials to kickstart my test project. Within this project, I wanted to implement a progress bar that visually represents the user's progression through fi ...

ReactJS Static Assets

Can anyone help me with serving txt files like robots.txt and verify.txt in a ReactJS app? For example: http://localhost:3000/.well-known/apple-developer-merchantid-domain-association.txt I have already tried placing the files in the public folder, but t ...

How to manage Apollo-wrapped children in test cases when mounting the React component

For the past few months, I've been immersed in working with ApolloJS within React (using react-apollo) and have encountered various tricks and challenges when it comes to unit testing components wrapped with Apollo. When testing a component directly ...

Encountering a problem with the navigation bar in the latest version of Next.js, version 13

"use client" import {Navbar, Button, Link, Text} from "@nextui-org/react"; import {styled} from "@nextui-org/react" const Box = styled("div", { boxSizing: "border-box", }); const AcmeLogo = () => ( ...

Is there a way to automatically incorporate a component into every view within a Next.js application?

Is there a more efficient and less cumbersome way to import components for every view in a Next.js app? I am interested in incorporating the "arwes" framework into my project and utilizing components from . One of the examples of a component I will be usin ...