Changes trigger the re-rendering of inputs

My modal is causing all inputs to be re-rendered with every change I make while typing.

I have a Formik object set up like this:

const formik = useFormik({
        enableReinitialize: true,
        initialValues: {
            sp_id: data?.id,
            websites: data?.websites || [],
            create_websites: [],
            delete_websites: [],
            update_websites: []
        },
        validationSchema: Yup.object({
            sp_id: Yup.string().required("This field is required and  can\'t not be changed"),
            websites:Yup.array().of(Yup. string())
        }),
        onSubmit: (values) => {
            console.log('submit:',values)
        }
    });

Custom Form Input Component:

const FormInput = ({ name, value, placeholder, ...rest }) => (
        <div className="space-y-1 w-full pt-3 pr-2">
            <label className="font-bold text-sm text-secondary">
                Web Link
                <span className="text-red-500">*</span>
            </label>
            <Input
                {...formik.getFieldProps(name)}
                value={value}
                placeholder={placeholder}
                onChange={(e) => {
                    formik.handleChange(e);
                    formik.setFieldValue(name, e.target.value);
                }}
                {...rest}
            />
        </div>
    );

I am also using Ant Design:

<Form.List name="websites">
                    {(fields, {add, remove}) => {
                        return (
                            (
                                <div key="test">
                                    {
                                        fields.map(({name, key, isListField, fieldKey, ...restField}) => {
                                            return (
                                                <div key={fieldKey}>
                                                    <Form.Item
                                                        {...restField}
                                                        name={[name, 'domain']}
                                                        fieldKey={[fieldKey, 'domain']}
                                                        validateTrigger={["onChange", "onBlur"]}
                                                        rules={[
                                                            {
                                                                required: true,
                                                                message: 'Domain is required'
                                                            }
                                                            
                                                        ]}
                                                        noStyle
                                                        className="w-full"
                                                    >
                                                        <div className="flex items-end w-full">
                                                            <FormInput
                                                                name={`websites.${key}.domain`}
                                                                placeholder="URL" 
                                                                value={formik.values.websites[key]?.domain}
                                                            />
                                                            {fields.length > 1 && (
                                                                <Button
                                                                    type="default"
                                                                    size="small"
                                                                    icon={<LuTrash2 size={20}/>}
                                                                    onClick={() => {
                                                                        if (formik.values.websites[key]) {
                                                                            formik.setFieldValue(
                                                                                'delete_websites',
                                                                                [
                                                                                    ...formik.values.delete_websites,
                                                                                    formik.values.websites[key]
                                                                                ]
                                                                            );
                                                                            remove(name)
                                                                        }
                                                                    }}
                                                                    className="mb-1 bg-[#F06548]  border-[#F06548] text-white flex items-center justify-center h-full"
                                                                />
                                                            )}
                                                        </div>
                                                    </Form.Item>
                                                </div>
                                            );
                                        }
                                    )}
                                    <div className="mt-5 w-full">
                                        <AntButton
                                            type="dashed"
                                            onClick={() => {
                                                add();
                                            }}
                                            icon={<PlusOutlined />}
                                            className="w-full border-2 border-dashed border-gray-500"
                                        >
                                            Add Website
                                        </AntButton>
                                    </div>
                                </div>
                            )
                        );
                    }}
                </Form.List>

The problem I'm facing is that each time I make a change, the input loses focus and gets re-rendered.

I'm looking for a smoother way to handle changes without causing unnecessary re-renders.

Answer №1

Instead of utilizing Ant Design's Form List, I opted to use Formik components such as Formik, Form, FieldArray, and Field.

const Index = ({data, isOpen, setIsOpen, mutate}) => {
  
  const validationSchema = Yup.object({});
  
  const initialValues = {};

  const handleSubmit = async (values, resetForm) => {};
  
  const handleAdd = (values, values) => {};
  
  const handleChange = (form, name, value) => {};
  
  return (
    <Formik
      initialValues={initialValues}
      validationSchema={validationSchema}
      enableReinitialize={true}
    >
      {(formikProps) => (
        <Modal {...actions}>
          <Form onFinish={() => handleSubmit(formikProps.values, formikProps.resetForm)}>
            {({ field, meta }) => (
                  <Input
                    {...field}
                    onChange={(e) => {
                      field.onChange(e);
                      handleChange(formikProps, field.name, e.target.value);
                    }}
                  />
            )}
          </Form>
        </Modal>
      )}
    </Formik>
  );
}

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

Integrating Octokit middleware in Next.js for enhanced functionality

Currently, I am in the process of honing my skills by creating a GitHub app. In Octokit, there is a feature called createNodeMiddleware that caught my attention. However, integrating it with next.js seems to pose some challenges. My main issue right now re ...

Encountering a flickering problem with the multiselect checkbox dropdown while attempting to integrate the React Syncfusion query builder component into the MUI Drawer component

I am currently working on integrating the React Syncfusion query builder into the MUI drawer. However, I am encountering a flickering problem with the multiselect checkbox when using the IN operator. If I place the query builder component outside of the M ...

Creating unique border-radius for each point in a Highcharts column chart with React

Let's flip the script and start at the finish line. My goal is to customize my column chart to resemble this design: https://i.stack.imgur.com/FckJB.png Creating this style is a breeze with chart.js Credit: I've already delved into this inquiry ...

Getting React Developer Tools to Function with Webpack

I recently followed a tutorial on how to expose React as a global variable in Webpack using the Expose module. Despite installing the Expose module and adding the appropriate loader configuration in the webpack.config.js file, I am still unable to access R ...

Encountering issues with a React + Node Shopify application

I am developing an app in Shopify using React + Node, but I encountered this error: Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. I'm not sure why ...

Tips for integrating a hubspot form into a Next JS component

I've been attempting to integrate a HubSpot form into a Next.js component without success so far. I followed the guidelines mentioned here, but have yet to figure it out. Where exactly should I place the embed code? As a newcomer to the realms of Rea ...

SignalR blocking axios requests (In a Waiting State)

I am currently developing a project that involves bidding on products in Auctions with real-time updates of the bid price. With potentially thousands or even millions of users worldwide participating in the bidding process. We have implemented SignalR for ...

Exploring the realm of styling with React JS

Currently, I am facing an issue while working with material-ui for my web design. Here is the code snippet that I am using: const useStyles = makeStyles((theme) => ({ card: { marginTop: theme.spacing(10), direction:"column", alig ...

Exploring the contents of a dropdown menu by navigating through a tree structure in React JS

A unique custom component has been developed, featuring a dropdown with a tree-like structure inside that allows users to search for values. However, it seems that the search function only works after reaching two levels of the tree structure. Currently, ...

A guide on customizing the dimensions and appearance of a Material UI modal in React JS: Applying width, height, and various styles

I'm having trouble implementing a material-ui modal in my React application. Although the modal is rendering in the browser, it's not behaving as expected. I tried looking at the material-ui API for guidance but didn't find any helpful infor ...

Exploring the array mapping technique in React with nested objects

As part of a school project, I am working on creating a dashboard to visualize some data. I have successfully loaded the data into the front end using React. Now my goal is to retrieve specific values from a large array. However, I am uncertain about how ...

Creating Bespoke Designs with Material UI

Upon visiting the Material UI landing page, I was impressed by its sleek design in terms of both layout and components. It got me wondering if I could implement this design instead of the default Material Design. Surprisingly, there seems to be a lack of ...

Unable to call component method after exporting with connect in React Redux

My React class component features a method that I would like to access later through the provider. Take a look at the class below: class ContactList extends Component { // props for contact renderContacts = () => { return // something }; ...

react component not displaying image

I must admit, this might be a silly question but I'm just starting out in web development. My goal is to create a clickable image component that redirects to another page on the website. However, despite not encountering any errors, the image is not ...

receiving a pair of components instead of just one

Here is the code for router.js: import React from 'react'; import { Route } from 'react-router-dom'; import CommentList from './containers/commentview'; import CommentDetalList from './containers/commentdetailview'; ...

Utilizing npm serve for Location Proxy

Is it feasible to implement a location proxy while serving a react application using npm install -g serve; serve -s build? For instance, redirecting any requests from https://example.com/api/* to https://example.com:8000/api/* ...

What is the best way to integrate the react-simple-captcha canvas element within an MUI Dialog component?

I've recently encountered an issue while trying to integrate react-simple-captcha into the submission form of my React app. The form is nested inside an MUI Dialog component on a specific page. Strangely, when the captcha element is not within a Dialo ...

Rendering on the client side

When using a server-side (.net app) application, only the necessary page is loaded to the client. However, in Client-Server applications (ReactJS + WebService), all pages are loaded on the client side. Does this initial load impact performance? ...

Discover the hidden truth: Unveiling the enigma of React

I'm currently learning React and I've been working on some apps to enhance my skills and deepen my understanding. Right now, I am facing a challenge where I need to incorporate the logged user information into the Redux state. However, whenever I ...

What steps should I take to fix the `Request is not defined` ReferenceError that keeps popping up whenever I try to execute the npm start command?

I keep getting an error that says 'ReferenceError: Request is not defined' every time I try to run npm start in my Node.js environment. The issue seems to be related to the file path "node_modules/@expo/server/src/environment.ts". Here's a ...