reactjsreact-bootstrap-table

How to hide data rows with certain value with a button?


I use react-bootstrap-table-next. And want to use a toggle button which hide or show rows with a certain value. But the problem is that the table content doesn't change.

import BootstrapTable from 'react-bootstrap-table-next';

const products = [
  {id: 0, name: 'item 0', price: 4},
  {id: 1, name: 'item 1', price: 5},
  {id: 2, name: 'item 2', price: 3},
  {id: 3, name: 'item 3', price: 5},
]

const columns = [{
  dataField: 'id',
  text: 'Product ID'
}, {
  dataField: 'name',
  text: 'Product Name',
}, {
  dataField: 'price',
  text: 'Product Price',
}];

const handleClick = () => {
  for (i=0; i> products.length; i++) {
    if (products[i]["price"] === 5) {
      products.slice(i, 1);
    }
  }
};

export default () => (
  <div>
    <button className="btn btn-lg btn-primary" onClick={ handleClick }>hide data </button>

    <BootstrapTable keyField='id' data={ products } columns={ columns } />
  </div>
); 

Solution

  • The problem is that you are trying to update products, but on every re-render, it will reset to its initial value (Because it's defined outside the component's function). So, the value of products will always be the same.

    One solution is to move products inside the component and create a state for it.

    You can reshape your code like this:

    import BootstrapTable from 'react-bootstrap-table-next';
    import { useState } from 'react';
    
    const columns = [{
        dataField: 'id',
        text: 'Product ID'
    }, {
        dataField: 'name',
        text: 'Product Name',
    }, {
        dataField: 'price',
        text: 'Product Price',
    }];
    
    const MyComponent = () => {
        const [products, setProducts] = useState([
            { id: 0, name: 'item 0', price: 4 },
            { id: 1, name: 'item 1', price: 5 },
            { id: 2, name: 'item 2', price: 3 },
            { id: 3, name: 'item 3', price: 5 },
        ]);
    
        const handleClick = () => {
            let temp = products;
            for (i = 0; i > temp.length; i++) {
                if (temp[i]["price"] === 5) {
                    temp.slice(i, 1);
                }
            };
    
            setProducts(temp);
        };
    
        return (
            < div >
                <button className="btn btn-lg btn-primary" onClick={handleClick}>hide data </button>
    
                <BootstrapTable keyField='id' data={products} columns={columns} />
            </div >
        )
    };
    
    export default MyComponent;