Utkarsh Goel
Utkarsh Goel

Reputation: 311

React - A component is changing a controlled input of type text to be uncontrolled

I am trying to sort my components

<input type="text" value={props.filters.text} onChange={(e) => {
            props.dispatch(setTextFilter(e.target.value));
        }} />
        {console.log(props.filters.sortBy)}
        <select value={props.filters.sortBy} onChange={(e) => {
            if (e.target.value === 'date') {
                props.dispatch(sortByDate());
            } else if (e.target.value === 'amount') {
                props.dispatch(sortByAmount());
            }
        }}>
            <option value="amount">Amount</option>
            <option value="date">Date</option>
        </select>

I am having an error in the select tag. Getting error A component is changing a controlled input of type text to be uncontrolled value of props.filters.sortBy initially is the date. When I try to change change it from the dropdown the error occurs.

Upvotes: 1

Views: 466

Answers (2)

Hamza Khan
Hamza Khan

Reputation: 1

This error occurs because you are trying to change an uncontrolled input to a controlled. Here the value of an input is based on the state of the component but during the first render the state is undefined it means input is uncontrolled but when you write something in the input field then it is controlled by the state and this error occurs. To get rid of this set your state as an empty string (""). So the input field will be controlled by the state at first render.

Upvotes: 0

p-syche
p-syche

Reputation: 645

The root of your problem is the value of your <input>. If ReactJS receives undefined as the input value, that input is considered "uncontrolled" and you are not supposed to change it to "controlled".

There's a very thorough answer about uncontrolled inputs in ReactJS here.

Upvotes: 5

Related Questions