Search code examples
javascriptreact-table

How to make a header clickable in react table


I'm using react table and I want to make one of my headers clickable, so when the user clicks it a drop down menu will appear. I know you can add a custom function for onRowClick like.

const onRowClick = cell => {
  return {
    onClick: () => {
      // do something here
    }
  }
}

But is there a way to do that in the header cell only? Are you supposed to add it to your columns, like.

const columns = React.useMemo(() => [
  {
    Header: 'Header',
    accessor: 'header',
    onClick: () => // do something
  }
])


Solution

  • You can make a custom function like onRowClick, but for your headers, here is one.

    const onHeaderClick = () => {
          return {
            onClick: () => {
              // do something
            },
          };
      };
    

    then pass it down to your table component

    <Table
        clickableHeader={onHeaderClick}
    />
    

    then in your table component you can call it in your th component like this

    <th
    {...clickableHeader(column)}
    >