How do you call a function in a react-table accessor? (reactjs)

ann mcg picture ann mcg · Aug 2, 2019 · Viewed 11.7k times · Source

I am modifying a ReactJS component. I have added a react-table to get the pagination, which works beautifully. But one of the columns in the table needs to call a function that is also in this component, so it can render a link depending on the content of that record. (Some results will render a link, some will not.) When I list the function in the accessor property of the column, it returns some of the values from the function, but not all of them. So, the link comes back as:

    localhost:3000/view/c/IDnumber/undefined.  

Both the IDnumber and query should be returned, but the query parameter is "undefined".

I've tried listing the function in the accessor like:

    getSerialNo(hit,query)

But then I get "hit is not defined". I've searched on this site and others to find a solution.

The column looks like:

    {id:'serialno',
    Header: "Serial #",
    accessor: getSerialNo
    }

The function, in part, looks like:

    const getSerialNo = (hit, query) => {
        const linkAs = '/view/c/${hit._id}/${query}'
    return <Link href={link} as={linkAs}><a target="_blank">{serialNo}
     </a></Link>

I would like to get back a link that actually includes the query, like:

    localhost:3000/view/c/IDnumber/query

Answer

Mina Fawzy picture Mina Fawzy · Oct 3, 2019

according to documentation

accessor: String | Function

Required This string/function is used to build the data model for your column. The data returned by an accessor should be primitive and sortable. If a string is passed, the column's value will be looked up on the original row via that key, eg. If your column's accessor is firstName then its value would be read from row['firstName']. You can also specify deeply nested values with accessors like info.hobbies or even address[0].street If a function is passed, the column's value will be looked up on the original row using this accessor function, eg. If your column's accessor is row => row.firstName, then its value would be determined by passing the row to this function and using the resulting value.

Its accept both string or function but make sure you set the id, you can do any operation on the row like row.attrbuiteName === null ? "no thing" : row.attrbuiteName

{
     id:'serialno',
     Header: "Serial #",
     accessor: row => row.attrbuiteName
     }

Reference:

https://github.com/tannerlinsley/react-table/blob/master/docs/api.md

Note in case using the function you must provide id in row