React throws an error message when the update depth surpasses its maximum limit

I am facing an issue with my container setup where the child container is handling states and receiving props from the parent. The problem arises when I have two select statements in which onChange sets the state in the child container, causing it to re-render unexpectedly. Strangely, despite checking only once, the render() and setState() codes are triggered repeatedly (verified using debugger). Below is the code snippet for my Select combobox:

                <Select
                    native
                    name="evidenceNode"
                    value={nodeType}
                    onChange={this.handleChange('nodeType')}
                    className={classes.textField}
                >
                    <option />
                    {NODE_TYPE.map(function (item, i) {
                        return <option key={i} value={item}>{item}</option>
                    })}
                </Select>

                <Select
                    native
                    name="modelType"
                    value={modelType}
                    onChange={this.handleChange('modelType')}
                    className={classes.textField}
                >
                    <option />
                    {MODEL_TYPE.map(function (item, i) {
                        return <option key={i} value={item}>{item}</option>
                    })}
                </Select>

The handleChange function responsible for setting the state:

handleChange = name => event => {
    this.setState({
        [name]: event.target.value,
    });
};

I believe there's a simple fix for this issue, but I can't seem to figure out where I am going wrong.

Here are some of the troubleshooting steps I've taken:

  1. Changed the way I call handle change to an arrow function, but it didn't resolve the issue.
  2. Removed one of the Select statements and tested again, which worked successfully.
  3. Tried removing the handleChange call from one of the Select statements, and everything ran smoothly.

Additionally, I'd like to mention that I have a componentWillReceiveProps function (not sure if it affects the situation):

componentWillReceiveProps(nextProps, nextContext) {
    if(nextProps.selectedNode !== this.state.selectedNode){
        this.setState({
            selectedNode: nextProps.selectedNode
        });
    }
}

Answer №1

The problem lies with the line

onChange={this.handleChange('modelType')}
.

Instead of attaching an event, you are actually invoking a method with that syntax.

This is leading to an infinite loop because each call to this.handleChange('modelType') triggers a re-render which in turn calls this.handleChange('modelType') again, and so on.

To fix this issue, attach an anonymous function to the onChange event that then calls the handleChange method:

onChange={e => this.handleChange('modelType', e)}

Additionally, make sure to update the parameters of the handleChange function as follows:

handleChange = (name, event) => {}

Answer №2

The issue did not lie with the handleChange listener. It turns out that [Material-UI]https://material-ui.com/ (the tool utilized for form elements) required a FormControl element to be added above each Select component. Therefore, the component structure should resemble the following:

<FormControl
                // className={classes.formControl}
            >
                <Select
                    native
                    name="nodeType"
                    value={nodeType}
                    onChange={this.handleChange('nodeType')}
                    className={classes.textField}
                    inputProps={{
                        name: 'nodeType',
                        id: 'nodeType'
                    }}
                >
                    <option/>
                    {NODE_TYPE.map(function (item, i) {
                        return <option key={i} value={item}>{item}</option>
                    })}
                </Select>
            </FormControl>

The mistake I made was having one FormControl with two Select elements inside it. This specific requirement is not clearly outlined on their official website.

I suspect that Material-UI invokes handleChange recursively on every Select component within the Form control, causing a loop in my case as I had more than one. Hopefully, this clarification proves helpful.

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

Reduce the identification number within a JSON array following the removal of an item

Within my local storage, I maintain a dynamic array. Each entry is accompanied by an ID that increments sequentially. If a user opts to delete an entry, it should be removed from the array while ensuring that the IDs remain in ascending order. For example: ...

In Visual Studio 2022, curly braces are now positioned on the same line for JavaScript code

I'm struggling with keeping Visual Studio from moving my curly braces to a new line whenever I auto format the code. Here's an example: Let's say I write this code: $('#details-modal').on('change', '#Foo1', fun ...

"Enhance your software with a customizable interface or develop new functionalities to generate analogous

Having API data with a similar structure, I am looking to streamline my code by filtering it through a function. However, as someone new to TypeScript, I am struggling to implement this correctly using a function and an interface. Essentially, I aim to ach ...

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 ...

React with Typescript: It appears that you are attempting to utilize Typescript without having it properly installed on your system

I am embarking on creating a React application integrated with TypeScript. Initially, I visited the React website to seek guidance on incorporating TypeScript in my project. The website directed me to execute the following command in the terminal: npx crea ...

Grabbing a section of a URL through a bookmarklet: A simple guide

Recently, I've been using this handy bookmarklet: javascript:currentUrl=document.location.href;document.location.assign(currentUrl+'embed'); This neat tool grabs the current URL, such as www.example.com/knZg_INW8fL/, and adds embed to it f ...

Dealing with lag problems while feeding a massive dataset into the Autocomplete component of Material-UI

In my React project, I have integrated the Autocomplete component from Material-UI to enhance user experience. However, when attempting to pass a large dataset of 10,000 items to the Autocomplete component as a prop, there is a noticeable delay of approxim ...

Utilizing AJAX and JavaScript to generate a table using the AJAX response and placing it within a <div> element

I am currently passing the response of this action in text form, but I would like to display it in a table format. Is there a way to do this? function loadAditivos(){ $('#aditivoAbertoInformacoesTexto').html('<div id="loaderMaior ...

The animation unexpectedly resets to 0 just before it begins

Currently, I am developing a coverflow image slider with jQuery animate. However, there are two issues that I am facing. Firstly, when the animation runs for the first time, it starts at `0` instead of `-500`. Secondly, after reaching the end and looping b ...

Tips for using Selenium and Javascript executor to search through the Canvas system?

Is it possible to automate interaction with a 'graph' created on a canvas? I need to be able to click on elements, drag them, and perform other actions like getting text. Can this be achieved with automation using Selenium and JavaScript executor ...

ObjectArray in Node.js

Building an object array in my node app involves transforming another object array. Let's assume the initial object array is structured like this... levels: [ { country_id: 356, country_name: "aaa", level0: "bbbb", level1: "cccc", level2: "dddd", le ...

Is it possible for two components to send two distinct props to a single component in a React application?

I recently encountered a scenario where I needed to pass a variable value to a Component that already has props for a different purpose. The challenge here is, can two separate components send different props to the same component? Alternatively, is it po ...

There are various IDs in the output and I only require one specific ID

I have a JSON fetcher that is functioning properly. However, whenever I request an ID, it returns all the IDs present in the JSON data. Is there a way to retrieve only the latest ID? This is my first time working with JSON so I am still learning. $(docu ...

Integrating domain name into a post request using React

Currently, I have a frontend (react, Node.js) and a backend Springboot hosted on the same remote hosting service at . The frontend and backend are placed in different environments but function well individually. I connected my frontend to a domain and up ...

Is there a way to download and store the PDF file created using html2pdf in Node.js on my local machine?

I have successfully generated a PDF using html2pdf, but now I want to either send it to my server in Node.js or save it directly onto the server. Currently, the PDF is downloaded at the client's specified path, but I also need a copy saved on my serve ...

Combine various input data and store it in a variable

I am looking for a way to add multiple input text values together and store the sum in a variable. Currently, I can add the values and display it in an id, but I want to assign it to a variable instead. The condition for this variable is described below af ...

Smooth-scroll plugin does not activate active state (due to JS modification)

I'm currently facing an issue with a script that handles smooth scrolling and the active state on my main navigation. The plugin in question can be found at: It's important to note that the navigation bar is fixed and therefore has no height. T ...

Is it possible to incorporate an additional value into the jQuery widget 'Autocomplete' by using a second variable?

For several years, I have been utilizing the jQuery 'Autocomplete Widget' in my projects. This plugin allows me to pass a value labeled as 'term' to the PHP SQL code that works like this: $( "#cs1" ).autocomplete({ aut ...

What are the steps to update your profile picture using Angular?

In my Angular 6 application, I am implementing an image upload feature with the following code: Html: <img [src]="url ? url : 'https://www.w3schools.com/howto/img_avatar.png'"> <br/> <input type='file' (change)="onSelec ...

What is the meaning of MVVM "binder" and how is it used?

I've been conducting research online to gain a deeper understanding of the MVVM architecture in general. According to Wikipedia, the key components of the MVVM pattern are: Model View View Model Binder This is the first time I have come across the ...