Categories
JavaScript Answers

How to fix the ‘React a component is changing an uncontrolled input of type checkbox to be controlled’ error with JavaScript?

Spread the love

Sometimes, we need to fix the ‘React a component is changing an uncontrolled input of type checkbox to be controlled’ error with JavaScript.

In this article, we’ll look at how to fix the ‘React a component is changing an uncontrolled input of type checkbox to be controlled’ error with JavaScript.

How to fix the ‘React a component is changing an uncontrolled input of type checkbox to be controlled’ error with JavaScript?

To fix the ‘React a component is changing an uncontrolled input of type checkbox to be controlled’ error with JavaScript, we should make sure the value prop always has a value set.

For instance, we write:

import React from "react";

export default function App() {
  const [name, setName] = React.useState();

  return (
    <div>
      <input value={name ?? ""} onChange={(e) => setName(e.target.value)} />
    </div>
  );
}

to define the name state with useState and didn’t set an initial value for name.

Then we add the input with the value prop set to name.

If name isn’t defined, we set it to an empty string.

As a result, the ‘React a component is changing an uncontrolled input of type checkbox to be controlled’ error won’t be thrown.

Conclusiun

To fix the ‘React a component is changing an uncontrolled input of type checkbox to be controlled’ error with JavaScript, we should make sure the value prop always has a value set.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *