Topic: Datatables filter not working with html in the columns

Ahmad Baig free asked 4 years ago


Datatables sorting and search is not working in the columns having HTML in them


Konrad Stępień staff answered 4 years ago


Hi @Ahmad Baig,

Try this code:

import React from 'react';
import { MDBDataTable } from 'mdbreact';

const DatatablePage = () => {
  const data = {
    columns: [
      {
        label: 'Name',
        field: 'name',
        sort: 'asc',
        width: 150
      },
      {
        label: 'Position',
        field: 'position',
        sort: 'asc',
        width: 270
      },
      {
        label: 'Office',
        field: 'office',
        sort: 'asc',
        width: 200
      },
      {
        label: 'Random Word',
        field: 'random',
        sort: 'asc',
        width: 50
      }
    ],
    rows: [
      {
        name: 'Tiger Nixon',
        position: 'System Architect',
        office: 'Edinburgh',
        random: <h5 searchvalue={'tourist'} >tourist <span className="badge badge-danger">narrow</span></h5>
      },
      {
        name: 'Garrett Winters',
        position: 'Accountant',
        office: 'Tokyo',
        random: <h5 searchvalue={'expression'} >expression <span className="badge badge-danger">popular</span></h5>
      },
      {
        name: 'Ashton Cox',
        position: 'Junior Technical Author',
        office: 'San Francisco',
        random: <h5 searchvalue={'rule'} >rule <span className="badge badge-danger">estimate</span></h5>
      },
      {
        name: 'Cedric Kelly',
        position: 'Senior Javascript Developer',
        office: 'Edinburgh',
        random: <h5 searchvalue={'announcement'} >announcement <span className="badge badge-danger">preparation</span></h5>
      },
      {
        name: 'Airi Satou',
        position: 'Accountant',
        office: 'Tokyo',
        random: <h5 searchvalue={'preoccupation'} >preoccupation <span className="badge badge-danger">stock</span></h5>
      }
    ]
  };

  return (
    <MDBDataTable
      striped
      bordered
      hover
      data={data}
      sortRows={['random']}
    />
  );
}

export default DatatablePage;

You have to add searchvalue property for your HTML tag and pass for this property your value (number or string) for sort system.

And then you should set sortRows in MDBDataTable for pass what column has component or HTML tag.

You can check this page to see how this works. (Please find "With sorting component" example)

Best regards, Konrad.


somesh palakolanu free commented 3 years ago

Hi @Konrad Stępień,

I had the similar issue in React App, sort for column with anchor tag is not working. Adding searchvalue to anchor tag and sortRows in MDBDataTable made sorting worked on that column, but now search on DataTable is crashing and showing empty screen.I am using "mdbreact": "^4.26.1"Any help on this would be appreciated.


Piotr Glejzer staff commented 3 years ago

Konrad is not working here yet. I'm here to help you. Can you post your code about that?


Jay Pavasiya free answered 3 years ago


I have the same issue if any one fide solution plz share


Wojciech Staniszewski staff commented 3 years ago

Could you create a snippet or paste some code here? Or better describe the problem.


Ahmad Baig free answered 4 years ago


@Konrad Stępień here is my code. Search and sort are not working for the components of ChangeStatus and AssignInspections

orders.js

export const Inspections = props => {
    let data = [];
    let rows = [];
    const userContextData   =   useContext(UserContext)
    const header = [
        {},
        {label: "Address", field: "address"},
        {label: "City", field: "city"},
        {label: "State", field: "state"},
        {label: "Type", field: "type"},
        {label: "Bank", field: "bank"},
        {
            label: "Client Name",
            field: "clientName"
        },
        {
            label: "Date Ordered",
            field: "dateOrdered"
        },

        {
            label:
                Path.urlRoute() === "my_inspections"
                    ? "Inspection Date"
                    : "Inspection Date",
            field:
                Path.urlRoute() === "my_inspections"
                    ? "inspectionDateAssign"
                    : "inspectionDate"
        }
    ];

    if (Path.urlRoute() === "inspections")
        header[header.length] = {
            label: "Assign",
            field: "assignInspection"
        };

    header[0] = {
        label: Path.urlRoute() === "my_inspections" ? "Status" : "Status",
        field: Path.urlRoute() === "my_inspections" ? "changeStatus" : "status",

    };

    const renderInspectors = order_id  => {
        const ele = document.getElementById('inspector'+order_id.target.id)
        const current   =   order_id.target;

        current.style= {display: 'none'}
        ele.style= {display:"block"}
    }
    if (props.inspections) {
        for (let index in props.inspections) {
            const row = props.inspections[index];
            let status = row.order_status;
            if (row.order_status === 'accepted') {
                status = 'Pending';
            }

            rows.push({
                address: <NavLink to={`/inspections/${row.id}`} searchvalue={row.address}>{row.address}</NavLink>,
                city: row.city,
                state: row.state,
                type: row.type,
                bank: (
                    <NavLink to={`/banks/${row.bank_id}`} className="my-0" searchvalue={row.bank_name}>
                        {row.bank_name}
                    </NavLink>
                ),
                clientName: (
                    <NavLink to={`/clients/${row.user_id}`} searchvalue={row.client_name}>{row.client_name}</NavLink>
                ),
                status: (

                    <span className={`badge text-white ${statusColorCodes[row.order_status]}`} searchvalue={status}>
                      {String.capitalizeFirstLetter(status)}
                    </span>
                ),
                dateOrdered: props.inspections[index].created_at,
                assignInspection: (
                        <div searchvalue={row.inspector_name}>
                            {
                                (JSON.parse(userContextData.user).role === 'Senior Inspector')?<span onClick={renderInspectors} id={row.id}>{row.inspector_name}</span> : ''
                            }

                            <AssignInspection
                                inspectors={props.inspectors}
                                orderID={row.id}
                                assignee={row.assignee}
                            />
                        </div>


                ),
                changeStatus: <div searchvalue={status}><ChangeStatus status={row.order_status} order={row.id}/></div>,
                inspectionDateAssign: (
                    <InspectionDate order={row.id} inspectionDate={row.inspection_date}/>
                ),
                inspectionDate: row.inspection_date
            });
        }
    } else {
        rows = {};
    }

    if (rows) {
        // console.log(rows);
        data = {
            columns: header,
            rows: rows
        };
    }

    return (
        <div className="block block-rounded p-3">
            <MDBDataTable
                striped={true}
                small={true}
                barReverse={true}
                data={data}
                entries={50}
                entriesOptions={[20, 30, 50, 100]}
                searching={true}
                noBottomColumns={true}
                sortRows={['address', 'bank', 'clientName', 'status', 'changeStatus', 'assignInspection']}
            />
        </div>
    );
};

ChangeStatus.js

export const ChangeStatus = props => {
  const userContextData = useContext(UserContext);
  const [status, setStatus] = useState(props.status);
  console.info(props)
  const changeStatus = (status, order) => {
    InspectionsService.setInspectionStatus(userContextData.accessToken, {
      order,
      status
    })
      .then(response => {
        console.log(response);
        setStatus(response.status);
      })
      .catch(error => console.log(error));
  };
  let statuses = {
    pending: "Pending",
    scheduled: "Scheduled",
    delayed: "Delayed",
    inspected: "Inspected",
    review: "Review",
    approved: "Approved"
  };

  statuses = Object.keys(statuses).map(function(key, index) {
    return (
      <Dropdown.Item key={index} onClick={e => changeStatus(key, props.order)}>
        {statuses[key]}
      </Dropdown.Item>
    );
    // statuses[key] *= 2;
  });


  return (
    <Dropdown>
      <Dropdown.Toggle
        variant="success"
        id="dropdown-basic"
        className={`badge border-0 ${statusColorCodes[status]}`}
      >
        {String.capitalizeFirstLetter(status)}
      </Dropdown.Toggle>
      <Dropdown.Menu>{statuses}</Dropdown.Menu>
    </Dropdown>
  );
};

AssignInspections.js

export const AssignInspection = props => {
  const userContextData = useContext(UserContext);
  const [assignee, setAssignee] = useState("");
  const [isAssigned, setIsAssigned] = useState(false);
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    setAssignee(`{"assignee":"${props.assignee}","order":"${props.orderID}"}`);
    if (props.assignee) setIsAssigned(true);
  }, []);
  let inspectors = "";
  if (props.inspectors && props.orderID) {
    inspectors = props.inspectors.map(inspector => {
      return (
        <option
          value={`{"assignee":"${inspector.id}","order":"${props.orderID}"}`}
          key={inspector.id}
        >
          {inspector.name}
        </option>
      );
    });
  }

  const onInspectorSelect = e => {
    setIsLoading(true);
    setAssignee(e.target.value);
    if (e.target.value) {
      InspectionsService.assignInspection(
        userContextData.accessToken,
        JSON.parse(e.target.value)
      )
        .then(response => setIsLoading(false))
        .catch(error => console.log(error));
    }
  };

  const assignToSelf = e => {
    setIsLoading(true);
    const payload = {
      assignee: JSON.parse(userContextData.user).id,
      order: props.orderID
    };

    InspectionsService.assignInspection(userContextData.accessToken, payload)
      .then(response => {
        setIsLoading(false);
        setIsAssigned(true);
      })
      .catch(error => console.log(error));
  };

  const unassignToSelf = e => {
    setIsLoading(true);
    const payload = {
      assignee: "",
      order: props.orderID
    };

    InspectionsService.assignInspection(userContextData.accessToken, payload)
      .then(response => {
        setIsLoading(false);
        setIsAssigned(false);
      })
      .catch(error => console.log(error));
  };

  if (isLoading) {
    return <BarLoader />;
  } else {
    return (
      <>
        {JSON.parse(userContextData.user).role === "Senior Inspector" ? (
          <select
            onChange={onInspectorSelect}
            className="form-control form-control-sm m-0  p-0"
            style={{ fontSize: "0.75rem", height: "auto", display: 'none' }}
            value={assignee}
            id={`inspector`+props.orderID}

          >
            <option value={`{"assignee":"","order":"${props.orderID}"}`}>
              ----
            </option>
            {inspectors}
          </select>
        ) : (
          <>
            {isAssigned ? (
              <button
                className="btn btn-sm btn-danger"
                onClick={unassignToSelf}
              >
                <i className="fa fa-user-alt-slash"></i>
              </button>
            ) : (
              <button className="btn btn-sm btn-success" onClick={assignToSelf}>
                <i className="fa fa-user-tag"></i>
              </button>
            )}
          </>
        )}
      </>
    );
  }
};

Konrad Stępień staff commented 4 years ago

Hi @Ahmad Baig,

Can you restore your project on our snippets or on CodeSandbox?

Your project seems for extended and I can't restore it on my CRA.

Best regards, Konrad.


Ahmad Baig free answered 4 years ago


@Konrad Stępień, this solved my issue but not working with select boxes in the column. Any help on that would be appreciated


Konrad Stępień staff commented 4 years ago

Hi, please send me your code and I will try to help you.


Ahmad Baig free commented 4 years ago

@Konrad Stępień, please see the answer below



Please insert min. 20 characters.

FREE CONSULTATION

Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.

Status

Answered

Specification of the issue

  • ForumUser: Free
  • Premium support: No
  • Technology: MDB React
  • MDB Version: 4.22.0
  • Device: PC
  • Browser: Firefox
  • OS: Ubuntu
  • Provided sample code: No
  • Provided link: No