reactjsdatatablereact-data-table-component

React DataTable insert action link


Good afternoon! I have react-data-table-component

I'm trying to create a column that will have action buttons (delete/edit...) To do this, in clickHandler I need to pass parameters from data, for example ID or possibly even additional parameters. At the moment I'm trying to pass one ID parameter and I'm not getting anything

function DataBase (){

    const clickHandler = (state) => {
        console.log("ID",state.target.id);
    };

    const data = ([
        {
            id: 1,
            title: 'Beetlejuice',
            year: '1988',
            action: "d-1",
            cell:(row) => <a href={row.title} onClick={clickHandler} id="d1">Action</a>,
        },
        {
            id: 2,
            title: 'Ghostbusters',
            year: '1984',
            action: "d-2",
            cell:(row) => <a href={row.title} onClick={clickHandler} id="d-2">Action</a>,
        },
    ]);

    const columns = [
        {
            name: 'Title',
            selector: row => row.title,
            sortable: true,
        },
        {
            name: 'Year',
            selector: row => row.year,
        },
        {
            name: 'Action',
            selector: row => row.action,
            cell: () => <a href="#" onClick={clickHandler}>Action</a>,
            ignoreRowClick: true,
            allowOverflow: true,
            button: true,
        },
    ];

return (
            <PageWrapper>
                <DataTable
                 columns={columns}
                 data={data}
                 pagination
               />
            </PageWrapper>
        );
}

export default DataBase;


}

No matter how I tried I can't get the ID in clickHandler

enter image description here

Please help me to solve this problem


Solution

  • You need to get the props from the cell and pass down the props to click handler like,

      cell: (props) => (
        <a
          href="#"
          onClick={() => {
            clickHandler(props);
          }}
        >
          Action
        </a>
      );
    

    And in clickHandler get it like,

      const clickHandler = (state) => {
        console.log("ID ", state.id);
      };
    

    Working Example:

    Edit charming-hamilton-1b2lfq