Search code examples
reactjsinputfilterdatatablereact-data-table-component

React warning: A component is changing an uncontrolled input to be controlled in `react-data-table-component-with-filter`


Problem description

I’m using the react-data-table-component-with-filter library to implement a table with column filters. However, when I type in the filter input of any column typing an existing value, everything works fine, but when I type an unexistent value in that column, I encounter the following warning in the console:

Warning: A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.

From what I understand, this warning typically appears when an input's value changes from undefined to a defined value (e.g., an empty string), causing React to treat it as controlled when it was initially uncontrolled. However, I’m not manually controlling the input; it is handled internally by the library.

My data array is initialized as an empty array (useState([])) and in cases where the fetched data is unavaiable or an error occurs, I explicitly set it to an empty array ([]).

Filtering is working fine, but this error in the console is annoying me.

It's not the usual A component is changing an uncontrolled input to be controlled problem, because the uncontrolled/controlled input it's suposed to be controlled by the library (react-data-table-component-with-filter)


Solution

  • In case this helps anyone:

    The library does not manage the filter value on its own; instead, it leaves the control to us. My issue was that I didn't know how to access the filter value (the text entered in the filter input). Now I've found that you can control that component passing an argument in the onFilter option, like this:

          <DataTable
            columns={columns}
            data={filteredData}
            responsive={true}
            pagination
            paginationPerPage={20}
            noDataComponent={t("scrape.noData")}
            defaultSortAsc={false}
            onFilter={(a) => {
              a["Media extension"]?.column.filterValue ? setFilterText(a["Media extension"]?.column.filterValue) : setFilterText("");
            }}
          />
    

    Hope this helps someone facing the same 'issue' with this library!