7

I am using react-table. I have defined onRowClick() function for a column. Here select text should highlight the text and clicking have to redirect to another page. Now when I try to select the text, its getting redirected. How to select text without triggering click event?

Following is my onRowClick function:

onRowClick = (state, rowInfo, columnInfo) => {
  return {
    onClick: (e, handleOriginal) => {
      if (columnInfo.id) {
        this.props.history.push(`/downloads/${rowInfo.original.id}`);
      } else if (handleOriginal) {
        handleOriginal();
      }
    }
  };
}

The following is my react-table component:

<ReactTable
  manual
  getTdProps = {this.onRowClick}
  data = {results}
  onFetchData = {this.onFetchData}
  sortable = {false}
  showPagination = {false}
  noDataText = 'no data found'
  columns = {[
   {
     Header: 'Id',
     maxWidth: 50,
     accessor: "id",
     Cell: (props) => <span className="btn-link pointer">{props.value} </span>
   },
   {
     Header: 'Processed on',
     maxWidth: 165,
     accessor: "created_at",
     Cell: (props) => <span> {this.getDateTime(props.value)} </span>
   }
  ]
/>

Clicking on id column should redirect to the details page. Selecting text should select the id text.

Beu
  • 1,370
  • 10
  • 23

1 Answers1

10

I think onclick cannot be prevented but your desired result can be obtained by using Window.getSelection() method.

The Window.getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.

By using this method you can get the selected text and then you can calculate its length as:

window.getSelection().toString()

And then you can modify your onRowClick method as given below:

onRowClick = (state, rowInfo, columnInfo) => {
    return {
        onClick: (e, handleOriginal) => {
            let selection = window.getSelection().toString();
            if(selection.length <= 0) {
                if (columnInfo.id && selection.length > 0) {
                    console.log("columnInfo.id", columnInfo.id);
                    this.props.history.push(`/downloads/${rowInfo.original.id}`);
                } else if (handleOriginal) {
                    handleOriginal();
                    console.log("columnInfo.id", "nothing");
                }
            }
        }
    };
};

I have created a working demo.

Triyugi Narayan Mani
  • 3,039
  • 8
  • 36
  • 56