简体   繁体   中英

Go to a link when clicked inside a Table.Row with onClick

I have a table and I want each row to be clickable and when you click on it to go to that link (which is different for each row).

<Table.Body>
  {rows.map((row, rowIndex) => (
    <Table.Row
      key={idList && idList[rowIndex]}
      onClick={() => {
        <Link
          to={
            entityName && `/${entityName}/${idList[rows.indexOf(row)]}`
          }
        />;
      }}>
      ...
    </Table.Row>
  ))}
</Table.Body>

So I did it like above, added a component but doesn't work. It says:

Expected an assignment or function call and instead saw an expression no-unused-expressions

I'm using Table / Table.Row from Semantic UI and Link from react-router-dom . I cannot change the Table but the Link component isn't mandatory. It would be great anyway if it can redirect to that link when it's clicked.

Is it any way to do this?

One way would be is to use the history to navigate from the component. To get the history object, you either need to use the useHistory() hook which is available from react-router:5.1.0 or if you are using a older version of react-router

  1. you will have to add a method that does it:

Functional

const onNavigate = (entityName, idList) => () => {
  entityName && history.push( && `/${entityName}/${idList[rows.indexOf(row)]}`) // change accordingly 
}

Class

onNavigate = (entityName, idList) {
  return function () {
    return entityName && this.props.history.push( && `/${entityName}/${idList[rows.indexOf(row)]}`) // change accordingly 
  }
}

This method returns a function reference, so that the onCLick prop doesn't trigger it on render and some_props will be visible in the inside function thanks to Closures

  1. you pass the method to the onClick method:
<Table.Body>
  {rows.map((row, rowIndex) => (
    <Table.Row
      key={idList && idList[rowIndex]}
      onClick={onNavigate(enitityName, idList)}
    >
      ...
    </Table.Row>
  ))}
</Table.Body>

this way the click handler will receive the a function reference and should navigate to the according url

Using react-router to link inside the react application you can use the useHistory hook and push the new path.

import { useHistory } from "react-router-dom";

function Component() {
  let history = useHistory();

  return (
    <Table.Body>
      {rows.map((row, rowIndex) => (
        <Table.Row
          key={idList && idList[rowIndex]}
          onClick={() =>
            history.push(
              entityName && `/${entityName}/${idList[rows.indexOf(row)]}`
            )
          }
        >
          ...
        </Table.Row>
      ))}
    </Table.Body>
  );
}


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM