Issues with resetting React Material UI TextField when using the useForm hook reset function

Currently, I am working on a project where I am utilizing React and MUI. Within my forms, I have implemented the useForm hook from react-hook-form. Here is a snippet of how I am using it:

React.useEffect(() => {
   const defaultValues = new Provider();
   defaultValues.code = '123';
   defaultValues.name = 'some name';
   reset({...defaultValues});
}, []);

The TextFields in my form are structured like this:

<TextField
            id="codeInput"
            required
            label="Code"
            variant="outlined"
            error={!!errors['code']}
            helperText={errors['code'] ? errors['code'].message : ''}
            {...register('code')}/>
          <TextField
            id="nameInput"
            required
            label="Name"
            variant="outlined"
            style={{width: '75vw'}}
            error={!!errors['name']}
            helperText={errors['name'] ? errors['name'].message : ''}
            {...register('name')}/>

I have also attempted to set the values like so:

setValue('code', '123', {shouldDirty: true, shouldTouch: true});
setValue('name', 'some name', {shouldDirty: true, shouldTouch: true});

Yet, when displayed, the TextFields appear as shown in this image: https://i.stack.imgur.com/Zj5hh.png

Any suggestions on what might be causing this issue?

Answer №1

The issue ultimately stemmed from a problem with the TextField element. By manipulating the properties that govern the positioning and behavior of the label within the TextField, I was able to achieve the desired functionality for the component.

Here is an example of how this was accomplished:

const [labelProperties, setLabelProperties] = React.useState<any>({});
setLabelProperties({shrink: true});
.....
.....
<TextField
   InputLabelProps={labelProperties}/>

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

npm unable to locate the specified file

I'm currently following a tutorial on creating a Google Maps clone. After completing the build, I tried running the npm start command but encountered the following errors: npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Users\m ...

The Next.js React framework seems to be having trouble reading user input from a

I'm encountering an issue when attempting to save form email/password registration using Next.js as it is throwing an error. import {useState} from 'react' type Props = { label: string placeholder?: string onChange: () => void na ...

The findByIdAndUpdate() function lacks the ability to modify the collection

I'm encountering an issue when trying to update a product using mongodb and redux. It seems that the database is not reflecting the changes after I attempt to update the product. Can someone please assist me with this problem? Here is my product.js f ...

Transforming an array of strings to integers within a GraphQL query when they are incorporated

I need help finding a solution to pass an array of strings and embed it into a query while using React and GraphQL. The issue I'm facing is that even though the parameter is accepted as an array of strings, it gets converted to a string when embedded. ...

What is the best way to change the color of my Material Icons when I move my cursor over them?

Currently, I am integrating mui icons 5.2.0 into my React application. Although the icon appears on the page, it remains unchanged in color when I try to hover over it. Check out the snippet of code that I have implemented: import EditIcon from '@mu ...

Embed images within the JavaScript bundle

Here is my scenario: I have developed a components library for React. Within this library, there is a package bundled with Rollup that contains various assets, including a GIF picture used in one of the components. The specific component utilizing this p ...

troubleshooting a React project with express server faults

I am currently developing a React application and encountering an issue where I am trying to fetch data from an Express server. Upon checking the browser's console, I see this error: GET http://localhost:3000/api/products 404 (Not Found) Beneath th ...

Tips for making a single API call using React Query

I am building a visitor call system using React Query. I have a call button and I only want to make an API call when the button is pressed. However, the API keeps getting called every time the component is rendered. How can I prevent the component from m ...

Issue ( Uncaught TypeError: Trying to access a property of undefined ('data') even though it has been properly defined

One of my custom hooks, useFetch, is designed to handle API data and return it as a state. useFetch: import { useState, useEffect } from "react"; import { fetchDataFromApi } from "./api"; const useFetch = (endpoint) => { const [d ...

Avoid reloading the header component along with its APIs when navigating routes in React JS

I'm currently working on a web application using react js/next js and within it, I have various pages that make use of globally shared components like the Header and Footer. However, I am facing an issue where I want to prevent unnecessary re-renders ...

There seems to be a problem fetching the WordPress menus in TypeScript with React and Next

Recently I've started working on a project using React with TypeScript, but seems like I'm making some mistake. When trying to type the code, I encounter the error message: "TypeError: Cannot read property 'map' of undefined". import Re ...

You are unable to use multiple background colors on a material UI snackbar

Is there a way to apply multiple background colors to a material UI snackbar? I attempted using linear-gradient as shown below, but it didn't work. import Snackbar from 'material-ui/Snackbar'; const bodyStyle = { border: `2px solid ${co ...

Utilizing the map function to display elements from a sub array

I'm struggling to print out the comments using the map function in this code: class Postcomment2 extends React.Component { uploadcomment = () => { return this.props.post.comments.map((comment) => { return <div>{comment["comment"]}< ...

How to successfully load the google-map-react library

After installing the google-map-react library locally in my app, I verified that it is listed in my package.json under dependencies. The corresponding folder also exists in the node_modules directory. However, when attempting to reference the component con ...

Issue encountered while attempting to start React and Node.js: NPM error

I've encountered some errors in my Node.js and React.js project. I have a server and a React SPA, both working independently. When I use "concurrently" to start them together, I get the following errors: [0] npm ERR! missing script: servernpm run clie ...

What is the best way to trigger a dispatch every time there is a change in the state while using Redux?

Is there a way to save the state of a realtime database every time it changes? What is the best method for achieving this? Currently, I am triggering an update to the database immediately after updating the state. However, there are instances where the st ...

The Box element surpasses the height of the Grid component

Homepage Component <Box component="fieldset" sx={{borderRadius:2, height:"100%"}}> Application Structure Component <Grid container> <Grid item xs={4} > <Root/> </Grid> ...

The Selenide test encounters difficulties when trying to interact with the Material checkbox

Hello fellow developers. We have incorporated the Selenide framework into our project to create automated UI tests. With our recent switch to Material-UI, we encountered some technical issues with a seemingly simple checkbox. I am currently attempting to ...

Using the .get() method to retrieve Firebase documents results in an error message saying "'is not a function'"

I'm currently attempting to retrieve all the documents from a specific collection in Firebase using the following code snippet: const userCollectionRef = collection(db, currentUser?.uid) const snapshot = await userCollectionRef.get() for (const doc of ...

What is the best way to implement the "ripple effect" programmatically using MUI?

Is there a way to programmatically display the ripple effect on MUI's Buttons? The ripple effect currently works when the button is clicked, but I'm looking for a way to trigger it manually. Should I disable MUI's ripple effect and create m ...