MultiSelect does not update value when value state changes (PrimeReact UI)

https://www.primefaces.org/primereact/showcase/#/datatable https://www.primefaces.org/primereact/showcase/#/multiselect

I am using the PrimeReact library to create and customize a Data Table.

My table is dynamic and will build itself based on the data given to it. I am assigning different filters to each column depending on the column’s data type, but because there are a variable number of columns I must create the filters dynamically.

To accomplish this I am factoring out the filter logic into a separate class which contain their state and logic.

My issue is that the MultiSelect component I am using as a filter interface does not update its value when it’s value’s state is updated. After updating the state the value remains null. As the MultiSelect component does not have a reference to the previously selected values I can only choose one value at a time.

I think I am missing some understanding regarding class components, as I usually use functional components. I used a class component in this case so that I could access filterElement from the instantiated DropDownFilter class through DropDownFilter.filterElement() and use as a prop in the Column component.

import React from 'react'
import { MultiSelect } from 'primereact/multiselect';

class DropDownFilter extends React.Component {
  constructor(props) {
    super(props);
    this.multiSelRef = React.createRef();
    this.state = {
      selectedOptions: [],
    }

    // Added following two lines trying to fix issue but they did not alter behaviour
    this.onOptionsChange = this.onOptionsChange.bind(this)
    this.filterElement = this.filterElement.bind(this)
  }
 
  onOptionsChange = (e) => {
    this.props.dt.current.filter(e.value, this.props.field, 'in');
    this.setState({selectedOptions : e.value})
  }

  filterElement = () => {
    return (
      <React.Fragment>
        <MultiSelect
          ref={this.multiSelRef}
          value={this.state.selectedOptions}  //*** value is null even when selectedOptions has been updated after user chooses option.
                                              // Confirmed by viewing value through multiSelRef
          options={this.props.options}
          onChange={this.onOptionsChange}
          optionLabel="option"
          optionValue="option"
          className="p-column-filter"
        />
      </React.Fragment>
    )
  }

}

export default DropDownFilter;

Answer

I learned the state was not working in this case because I was instantiating the DropDownFilter using the new keyword in when using it. This means it wasnt being mounted to the DOM and could not use state.

I am still having issues regarding implementing the custom columns with filters, but I have posted a new question to handle that scope with my new findings.

Leave a Reply

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