Search code examples
javascriptreactjsmaterial-table

Material-Table in React. Dynamically setting table options with state variables


Im new to this Material-Table table. Im trying to set its options based upon what the user selects to do.

For example, I want to turn on/off filtering based upon if the user want to filter or not.

I have a button that sets a state variable true or false depending on when its selected.

    this.state = {
        filterStatus:false,
    }

But my options property doesnt allow me to use the state variable.

     options={{
           filtering: {this.state.filterStatus}
             }}

Is there a way to do this?

I want the user to be able to simplily have the option to turn off filtering with a push button.

To go from this,

enter image description here

to this

enter image description here


Solution

  • You can use filtering under options in MaterialTable as below:

    <MaterialTable
                title="Basic Filtering Preview"
                columns={state.columns}
                data={state.data}
                options={{
                    filtering: state.filtering
                }}
                icons={tableIcons}
            />
    

    In this example, I used a toggle button to trun off/on filtering.

    Here is the Code Sandbox