Canovice
Canovice

Reputation: 10243

ReactTable7 with simple tooltip when hovering <th> elements

TL/DR: Want to display tooltips when hovering headers using react-table (v7 with hooks).

I am attempting to create a simple tooltip for a table created in React using the new ReactTable library. I don't know how to import ReactTable into a Stackoverflow code snippet, but here is a forked version of an example table from the npm page for the library. I am attempting to modify this table to have proper tooltip headers. In this Code Sandbox, in the App.js where the columns array is created, I have added the following tipText key to the columns:

const columns = React.useMemo(
  () => [
    {
      Header: 'Name',
      columns: [
        {
          Header: 'First Name',
          accessor: 'firstName',
          tipText: 'Text for the First Name tooltip'
        },
        {
          Header: 'Last Name',
          accessor: 'lastName',
          tipText: 'Text for the Last Name tooltip'
        },
      ],
    },{
      ...

...so that I can use the tipText when rendering the Table to display the tooltip. I have changed the <thead> element rendering as well, to include a class for the th, and a span for the tooltip to display in:

<thead>
  {headerGroups.map(headerGroup => (
    <tr {...headerGroup.getHeaderGroupProps()}>
      {headerGroup.headers.map(column => (
        <th 
          className='new-tooltip' // added a new class
          {...column.getHeaderProps()}>{column.render('Header')}
          <span>Tooltip Text</span> // and a span for the tooltip (with the wrong text)
        </th>
      ))}
    </tr>
  ))}
</thead>

I've also added additional CSS styles to get the span to display on hover. Making these changes does display a tooltip, however it is not positioned correctly, and it does not have the correct text displaying. My two questions are then:

1: How can I pass the tipText into the rendering, in order to render the correct text in the tooltip?

2: How can I position the tooltip so that it is displayed in the correct spot (above its relevant <th> element)

Thanks!

Edit: if anyone has a link to any stackoverflow post that successfully renders a code snippet displaying a table from react-table v7, please share, as I'd like to update this post with a non-code-sandbox working example if possible

Upvotes: 4

Views: 11637

Answers (1)

gdh
gdh

Reputation: 13682

  1. You can simply render dynamic span
{headerGroup.headers[index].tipText && (
    <span>{headerGroup.headers[index].tipText}</span>
)}
  1. You need to make the td position relative
td {
      margin: 0;
      padding: 0.5rem;
      border-bottom: 1px solid black;
      border-right: 1px solid black;
      position: relative; //<---here

      :last-child {
        border-right: 0;
      }
    }

Working copy of your code

Edit aged-leftpad-6my7x

Upvotes: 5

Related Questions