Issues encountered when updating values in MaterialUI's TextField using Formik

Within my React functional component, I utilize Formik for form management and MaterialUI V5.10 for styling. The form includes TextField elements and a Canvas element.

I am encountering two issues...

Despite setting initial values in Formik, the TextFields do not display those values unless I use the 'defaultValue' property in the code below:

const initialValues = {
    toEmail01: "<user>@xyz.co",
};

return (
    <div>
        <Formik
            initialValues={initialValues}
            validationSchema={validationSchema}
            onSubmit={handleSubmit}
            //enableReinitialize={false}
        >
        {({
            submitForm,
            handleBlur,
            handleChange,
            isSubmitting,
            isValid,
            dirty,
            touched,
            values,
            errors,
        }) => (
            <Form>
                <div>
                    <Grid item xs={2}>
                        <Item
                            sx={{
                                width: "50em",
                                height: "20em",
                                variant: "outlined",
                                border: "solid",
                                overflow: "scroll",
                            }}
                        >
                            <Typography variant="">
                                To
                            </Typography>
                            <Box
                                component="form"
                                sx={{
                                    "& .MuiTextField-root": { m: 0, width: "75ch" },
                                }}
                                noValidate
                                autoComplete="off"
                            >
                                <div>
                                    <TextField
                                        id="toEmail01"
                                        name="toEmail01"
                                        //defaultValue={initialValues["toEmail01"]}
                                        onChange={handleChange}
                                        onBlur={handleBlur}
                                        helperText={
                                            touched.toEmail01 ? errors.toEmail01 : ""
                                        }
                                        error={
                                            touched.toEmail01 && Boolean(errors.toEmail01)
                                        }
                                        margin="dense"
                                        variant="standard"
                                        fullWidth
                                    />
                                </div>
                           
                            </Box>
                        </Item>
                    </Grid>
                </div>
            </Form>
            )}
        </Formik>

Another issue arises with a Canvas element on the Formik form that requires dynamic updates based on user input using the useState() hook. Each update causes a re-render of the entire component, refreshing the values of non-related TextInputs. I have tried enableReinitialize={false} and enableReinitialize with Formik without success in resolving this.

Answer №1

If you encounter difficulties updating the value of a MaterialUI TextField within a Formik context, consider trying this alternative method:

Utilize Formik's useFormikContext hook to retrieve the values and handleChange props:

import { useFormikContext } from 'formik';
import { TextField } from '@material-ui/core';

function MyCustomForm() {
  const { values, handleChange } = useFormikContext();

  return (
    <TextField
      name="customField"
      value={values.customField}
      onChange={handleChange}
      label="Custom Field"
    />
  );
}

Ensure that the name attribute of the TextField corresponds with the field name in your Formik values object.

By utilizing useFormikContext and assigning the handleChange function to the onChange property of the TextField, you can efficiently update the value of the TextField in synchronization with Formik's values.

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

Creating Multiple Result Lists in MUI Autocomplete Based on Option Properties: A Step-by-Step Guide

I have a query about displaying results using the MUI Autocomplete component. I am looking to categorize the results into two separate lists placed side by side. Currently, I have a working searchbar with one list of results. However, I aim to segregate t ...

In a Javascript scenario, only the initial button can successfully submit to an Ajax form even when having unique

Similar issues have been reported by other users when looping rows of buttons, often due to inadvertently reusing the same Id or value. I am facing a similar issue, but each of my buttons is unique. AJAX request <script> $(document ...

The way styleOverrides function behaves varies between MUI versions 4 and 5

Currently, I am in the process of upgrading MUI from version 4 to version 5 and encountering a new behavior with the overrides. In order to illustrate the issue effectively, I have set up two codesandbox environments with minimal code for both versions - ...

Utilize inherited autocomplete/suggestion prop types within the wrapping component

I am currently developing my own customized "wrapper" for a Chakra UI component. This wrapper allows me to include additional props, methods, and any other functionalities that I may require in the future. However, one drawback of this approach is that I ...

Angular: The Ultimate Guide to Reloading a Specific Section of HTML (Form/Div/Table)

On my create operation page, I have a form with two fields. When I reload the page using window.reload in code, I can see updates in the form. However, I want to trigger a refresh on the form by clicking a button. I need help writing a function that can r ...

Concealing URL parameters in ui-sref (using ui.router)

Here is the HTML code I am working with: <a ui-sref="videoParent.Display.video({videoName:'[[sVid.slug]]', videoId:'[[sVid.videoID]]'})"><p>[[sVid.name]]</p></a> The parameters videoName and videoId are retriev ...

Is anyone else experiencing differences in the appearance of my mega menu between Safari, Firefox, and Chrome? It seems like

When viewing in Safari, the text overlaps for some reason. It works fine on Firefox and Chrome. Here's a screenshot of the issue: Safari: https://i.stack.imgur.com/hf7v2.png Firefox: https://i.stack.imgur.com/NrOOe.png Please use Safari to test th ...

Invert the motion within a photo carousel

Is there anyone who can assist me with creating a unique photo slider using HTML, CSS, and JS? Currently, it includes various elements such as navigation arrows, dots, and an autoplay function. The timer is reset whenever the arrows or dots are clicked. Ev ...

Using WebRTC on a shared hosting environment (with SSH access) without the need for nodejs, ideally implemented in PHP

As I was exploring ways to integrate webRTC into a website that I am creating on shared hosting, I stumbled upon this GitHub repository by nielsbaloe. It has been incredibly helpful in establishing a basic connection. This particular code snippet appears ...

Managing the jQuery.noConflict function

Upon review, I noticed that the scripts I inherited start like this: var $j = jQuery.noConflict(); The purpose behind this code is not clear to me. While I understand the intent is to avoid conflicts, I am uncertain about the specific conflict it aims to ...

The conversion of Draft-js JSON to EditorState is not functioning correctly

Recently, I utilized Draft-js to generate blog posts. When a user creates a post, the data is transformed into a string and dispatched to the server for storage. The conversion of draft-js EditorState looked like this: JSON.stringify(convertToRaw(editorSta ...

In NextJS, where is the best place to run sensitive code to ensure it is only executed server-side?

I'm currently exploring the world of NextJS and I am in the process of figuring out how to structure my project with a solid architecture that prioritizes security. However, I find myself at a crossroads when it comes to determining the best place to ...

Tips for keeping the main section from scrolling while scrolling through the side navigation

Within my Angular application, I have implemented a sidenav and a main section. My desired behavior is to prevent any scrolling in the main section while I am scrolling in the sidenav, similar to the functionality seen on the Angular Material Design docume ...

The error message "Cannot construct apickli.Apickli" is indicating a Type Error

Encountering this issue : TypeError: apickli.Apickli is not a constructor every time I attempt to execute Sendpostrequest.js again in the following step of a scenario. In A.js, the initial call to Sendpostrequest works without any problems. However, ...

Struggling to display the sorted array items on the screen?

Within the realm of my jsfiddle experiment, my aim is to organize items based on price from highest to lowest by utilizing the following function: function mySortingFunction() { var elements = [].slice.call(document.getElementsByClassName("price")); e ...

Violation of Content Security Policy directive has occurred

During my full-stack project development, I encountered an issue with the inclusion of the bundle.js file in my base HTML file using a simple script tag. When trying to render the page and utilize the JS functionality, I faced a content security policy vio ...

What causes useEffect to trigger twice when an extra condition is included?

Attempting to create a countdown timer, but encountering an interesting issue... This code triggers twice in a row, causing the useEffect function to run twice per second. 'use client' import {useState, useEffect, useRef} from 'react' ...

Troubles with CSS in MUI Component Integration

How can I successfully implement a vertical timeline using Material UI in React? I've set it up, but the CSS isn't functioning as expected. Is there an error in my implementation? List of Dependencies: "@emotion/react": "^11.11.1& ...

Extracting information from a checkbox list displayed within an HTML table

I have a table with multiple rows and two columns in each row. The first column contains text, and the second column consists of checkboxes. While I was able to retrieve the values from the first column, I am struggling to fetch the values of the selected ...

Using Font Awesome Icons within material-ui Buttons

Can anyone help me figure out how to use fontawesome icons in my material-ui Button component? I've been struggling with this issue and could use some guidance. (I am working with React and react-admin framework.) import '../../../node_modules/f ...