How to filter for values inside an array of objects for React Table?

Viewed 32

I am using React Table and recently I got into an issue of not being able to search nested array of objects in my column data! This is my code so far.

    {
            Header: "competitors",
            accessor: "competitors",
            Cell: ({ cell }: { cell: CellProps<TableInstance> }) => (
              <div className="flex flex-wrap gap-y-1 items-center">
                {cell.value.map((competitor: Competitor, i: number) => {
                  return (
                    <div key={i}>
                      <span
                        key={i}
                        className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 mx-1"
                      >
                        {competitor.name}
                      </span>
                    </div>
                  );
                })}

Basically competitors is an array of object and in the cell, I change to values to just its name. Do help thank you! :)

1 Answers

I am able to solve this by using a custom accessor. This solution changes the data from array of objects to an array of string instead, making such that my global filter will work. I hope this help someone!

   {
            Header: "Competitors",
            // This is a custom accessor to get the string, name. Mainly for the search.
            accessor: (data: { competitors: Competitor[] }) => {
              const output: string[] = [];
              data.competitors.map((c) => {
                return output.push(c.name);
              });
              return output;
            },
            Cell: ({ cell }: { cell: CellProps<TableInstance> }) => {
              return (
                <div className="flex flex-wrap gap-y-1 items-center">
                  {cell.value.map((name: string, i: number) => {
                    return (
                      <div key={i}>
                        <span
                          key={i}
                          className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-800 mx-1"
                        >
                          {name}
                        </span>
                      </div>
                    );
                  })}

                  <MiniPlusButton onClick={() => console.log("asdasd")} />
                </div>
              );
            },
          },
Related