0

I have the following component hierarchy:

     App
      |
   |------|
Results  Form

So the Results and Form components are children of the App component. I am trying to implement controlled inputs in the Form. I have my state in the App component as I want to display the data from the form inputs in the Results component. I am getting the Warning: A component is changing an uncontrolled input to be controlled error when I don't set initial values for the state and try to use the form. When I set initial values in the state, these values are displayed in the inputs which is not what I want when a user first goes to the form. What is the best solution to this problem of having to set the state to avoid the React Warning but not wanting to display values in the input prior to the user even using the form?

1 Answers1

0

If you get such an error most likely because you don't have a state that handles the form input:

Here's an example:

App.js

import { useState } from "react";
import Form from "./Form";
import Result from "./Result";

export default function App() {
  const [input, setInput] = useState("");
  return (
    <>
      <Form input={input} inputHandler={setInput} />
      <Result result={input} />
    </>
  );
}

Form.js

export default function Form({ input, inputHandler }) {
  return (
    <form>
      <input value={input} onChange={(e) => inputHandler(e.target.value)} />
    </form>
  );
}

Result.js

export default function Result({ result }) {
  return <span>Your input is: {result}</span>;
}
Qudusayo
  • 1,026
  • 9
  • 15