Reputation: 3125
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?
Upvotes: 0
Views: 1868
Reputation: 3004
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
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
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
Upvotes: 1
Reputation: 360
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>
);
}
Upvotes: 0