Changing an Uncontrolled Input to Controlled Error in React
Gunnar Gissel

Gunnar Gissel @monknomo

About: Saving fish by writing code! Applications developer in fisheries, specializing in webapps and moving 'enterprise-y' legacy systems to modern agile systems - Email or tweet me if you want to talk!

Location:
Alaska
Joined:
Mar 24, 2017

Changing an Uncontrolled Input to Controlled Error in React

Publish Date: Jul 29 '17
11 0

React wants form inputs and the like to keep their state inside React, inside of inside the input. This style is called a "controlled input". They also offer "uncontrolled input" where the input manages its own state.

React apparently does not like inputs switching from controlled to uncontrolled. I was developing a form with the docs open next to my editor and I kept getting a Warning: CustomInput is changing an uncontrolled input of type text to be controlled. Input elements should not switch from uncontrolled to controlled (or vice versa). Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info:https://fb.me/react-controlled-components

As far as I could tell, my input was set up to always be controlled. I changed javascript around and googled for quite some time before realization set in

I was Switching a Form Value from '' to null

This is apparently a no-no in React's controlled component land. My initial state set up had all empty strings, and the only subsequent state manipulation was to get data from webservices. The webservices I'm working with return a fairly faithful representation of data from a database - nulls and all.

I solved it by converting my state variable to const in the render method - with a twist:

const nullable = this.state.nullable == null ? '' : this.state.nullable;
Enter fullscreen mode Exit fullscreen mode

A little sprinkling of last minute converters and all is well.

Get a monthly email with great tech and tech leadership articles from around the web

Thank you Sebastian Dooris for the sprinkles

If you like this, visit my blog for more

Comments 0 total

    Add comment