I’m havin a list of tasks and I wonder how do I route on the specific task clicked. Do I need to send a special Id param to the onclick handler ? So that every task has it’s own Id in the parent app.js component.
https://codesandbox.io/s/test-login-page-tasks-forked-vkxnxg?file=/src/components/Task.js
// App parent component
const Tasks = [
{
id: "001",
status: 0,
priority: 2,
title: "Develop website homepage",
description:
"Create a visually appealing and responsive homepage for the website",
schedule: {
creation_time: "2021-07-23T10:00:00"
},
author_name: "John Smith"
},
{
id: "002",
status: 1,
priority: 1,
title: "Implement user authentication",
description: "Add user authentication feature to the website",
schedule: {
creation_time: "2021-07-24T14:30:00"
},
author_name: "Sarah Lee"
}
]
function App() {
const [tasks, setTasks] = useState(Tasks);
return (
<BrowserRouter>
<div>
<Header />
<Switch>
<Route path="/" exact={true}>
<Login authors={Authors} />
</Route>
<Route path="/taskslist">
<Taskslist Tasks={tasks} />
</Route>
<Route path="/newtask">
<NewTask
authors={Authors}
onFinish={(newTask) => {
setTasks((pre) => [
...pre,
{ ...newTask, id: Math.random().toString() }
]);
}}
/>
</Route>
<Route path="/errorlogin">
<ErrorLogin />
</Route>
</Switch>
</div>
</BrowserRouter>
);
}
export default App;
// Parent taskslist component
import React from "react";
import { useHistory } from "react-router-dom";
import Task from "./Task";
const Taskslist = ({ Tasks, tasksAuthors }) => {
const history = useHistory();
return (
<div className="wrapper">
<h1>Tasks</h1>
<button >New Task</button>
<div className="tasks__wrapper">
<div className="tasks__tasks-item">
<h2>In queue</h2>
<Task Tasks={Tasks.filter((task) => task.status === 0)} />
</div>
<div className="tasks__tasks-item">
<h2>In progress</h2>
<Task Tasks={Tasks.filter((task) => task.status === 1)} />
</div>
<div className="tasks__tasks-item">
<h2>Completed</h2>
<Task Tasks={Tasks.filter((task) => task.status === 2)} />
</div>
</div>
<button>Back</button>
</div>
);
};
export default Taskslist;
// Child Task component
import React from "react";
import { useHistory } from "react-router-dom";
const Task = ({ Tasks }) => {
const history = useHistory();
const goToTask = () => { // send a task Id here ?
history.push("/task");
};
return (
<div className="wrapper" onClick={() => goToTask()}> // send a task Id here ?
{Tasks.map((task) => (
<div key={task.id}>
<h3>{task.title}</h3>
<h4>{task.author_name}</h4>
</div>
))}
</div>
);
};
export default Task;
2
Answers
This can be done using URL Parameters which is supported by
react-router
By using a special format for your URL path, you can pass variables inside the URL, which can be accessed using the
useParams
hook provided by React RouterAn example can be:
This notation of a variable name preceded by a
:
signifies a URL parameter.And inside the
TaskComponent.jsx
you can access this id as:You can find the official documentation here