Home > Blockchain >  React: Warning, a component is changing an uncontrolled input to be controlled
React: Warning, a component is changing an uncontrolled input to be controlled

Time:04-17

I'm using Google maps address autocomplete in my React app. It works by hooking into an input element, watching for changes, and providing a dropdown location select.

Relevant code:

<InputGroup hasValidation className="mb-3">
    <FormControl id="autocomplete"/>
</InputGroup>
useEffect(() => {
        
    // only specify the fields we need, to minimize billing
    const options = {"fields": ["address_components"]}

    const autocompleteElement = document.getElementById("autocomplete")

    if(autocompleteElement) {

        autocomplete.current = new google.maps.places.Autocomplete(autocompleteElement, options);
            
        const listener = autocomplete.current.addListener("place_changed", placeSelected);
        return function cleanUp() {
            google.maps.event.clearInstanceListeners(listener);
        }
    } else {
        // nothing to do yet
        return;
    }
});

However, I'm getting a warning in the browser console:

Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component

Seems obvious enough- the autocomplete functionality is changing the input itself as opposed to using react state to make a controlled component. However that's the way I want it. Is there a way I can silence this error? I've tried adding an empty defaultValue and an empty onChange function, but still got the error. Thanks in advance!

(There were a few questions with the same issue, but nothing about deliberately disabling the warning)

CodePudding user response:

Use a regular uncontrolled html input instead of one of the controlled react-bootstrap inputs.
You can use a ref to refer to the input.

<InputGroup hasValidation className="mb-3">
   <input
          defaultValue="Belgium"
          type="text"
          ref={this.autocomplete} />
</InputGroup>

More info on uncontrolled inputs and ref usage here:
https://reactjs.org/docs/uncontrolled-components.html

CodePudding user response:

You can try this :

<InputGroup hasValidation className="mb-3">
    <FormControl id="autocomplete" value={"Canada" || ''}/>
</InputGroup>

This will remove the warning.

  • Related