How can I link to the corresponding child React component using Link
from react-router-dom
? By passing an id to the url. Now I’m getting the id, but the component isn’t rendered.
https://codesandbox.io/s/test-login-page-tasks-rmfn5j?file=/src/components/Taskslist.js
Parent component
const ParentComponent = ({ Tasks }) => {
const params = useParams();
const id = params.id;
return (
<div className="wrapper">
{Tasks.map((task) => (
<div key={id}>
<h3>{task.title}</h3>
<h4>{task.author_name}</h4>
</div>
))}
</div>
);
};
Child component
Import Link from react-router-dom
<Link to="/task/:id">
<Task
goToTask={goToTask}
/>
</Link>
I’m trying to render the child component when clicking on its link at the Parent component list. So the url changes, but the Child component isn’t rendered and the window is empty. Maybe it’s not good using at the same time Link
and useParams
. I’m trying to get the child component id and pass so I can link to the specific child component.
2
Answers
You have a small typo in your router code. the code you have for the task id is
should be modified to this
you forgot the slash /
after that it should work fine.
what you will have after modification
The code is rendering links to the literal path
"/task/:id"
instead of "injecting" the task id value in to the target path.TaskList
Instead of wrapping an array of filtered tasks by status, filter then map each array of tasks to a link to the specific task.
Task
TaskComponent
App – the route being linked to is missing the leading
"/"
character.