Search code examples
reactjsreduxreact-reduxreact-hookscontrolled-component

React - set controlled input value from the Redux Store



I'm dispatching a redux action on onChange event on an input to add to some "answers" array on the Redux state.
Everything works fine and the Redux store gets updated, but the issue is when setting the input value to reflect the change in the Redux store, it gives me an error in the console that says ...

Warning: A component is changing an uncontrolled input of type number to be controlled.

Here's a codesandbox to demonstrate the issue ...

https://codesandbox.io/s/controlled-input-issue-p2k74

How can I make the input to be controlled, but via the Redux store, not the local state?


Solution

  • If you want to an input to be controlled, just pass a value every time to value prop of input element like, change this

    QuestionAnswerInput.js

    Change the input component to

      <input
        type="number"
        value={getInputValueFromStore(answers, questionId) || ""}
        onChange={e => handleAddNumericalAnswer(e)}
      />
    

    For more about controlled components refer this article