Reputation: 23
The dropdown menu will have a list of users who will be assigned to perform a specific task, so how to add & display those users dynamically using React JS
Upvotes: 0
Views: 224
Reputation: 1465
Based on your requirements, which are from my POV still vague, I could propose a following solution:
const {useState} = React;
const tasksInitialData = [
{
taskId: 1,
taskName: "Task 1",
taskDescription: "Task 1 description",
assignedUsers: [],
},
{
taskId: 2,
taskName: "Task 2",
taskDescription: "Task 2 description",
assignedUsers: [],
}
]
const users = [
{
userId: 11,
userFirstName: "John",
userLastName: "Smith",
username: "Johnny",
},
{
userId: 22,
userFirstName: "Peter",
userLastName: "Peterson",
username: "pp123",
},
{
userId: 33,
userFirstName: "Nick",
userLastName: "Nickolson",
username: "user-nick",
}
]
const App = () => {
const [tasks, setTasks] = React.useState(tasksInitialData);
// method checks does a given user (item) already exists in tasks.assignedUsers (collection)
// it is written so it is fairly generic
function isUserAlreadyAssigned(item, collection, propertyName) {
return collection.filter(collectionItem => collectionItem[propertyName] === item[propertyName]).length
}
function handleAssignUser(taskId, user){
setTasks(tasks.map(task => {
if(task.taskId !== taskId) return task
else {
return {
...task,
assignedUsers: [
...task.assignedUsers,
user
]
}
}
}))
}
return(
<div>
{tasks.map(task => {
const usersAvailableForTask = users.filter(user => !isUserAlreadyAssigned(user, task.assignedUsers, 'userId'));
return <div style={{padding: 10, margin: 10, backgroundColor: '#b7bac7'}}>
{task.taskName}<br/>
Users assigned for this task: {task.assignedUsers.map(assignedUser => `${assignedUser.userFirstName} ${assignedUser.userLastName} `)}<br/>
Assign users for this task:<br/>
<select name="users" id="user">
<option value="">--Please choose a user for this task--</option>
{usersAvailableForTask.map(user => <option value={user.userId} onClick={() => handleAssignUser(task.taskId, user)}>{`${user.userFirstName} ${user.userLastName}`}</option>)}
</select>
</div>})}
</div>
)
}
ReactDOM.render(<App />, document.getElementById("app"));
Idea is that you have a list of tasks (tasksInitialData
) (which you will obtain from backend), and every task has a list of users assigned to it (in this case an empty array, but in general it can be pre-filled).
Then you have a list of users (users
) - assumption is the list is autonomous, meaning it doesn't depend on the task(s). This list is displayed for every task. Once you select a user for a give task, he is omitted from the selection for this task.
Please have in mind this is an MVP of the solution, and it can be improved in many ways. One of possible imporvements:
useMemo
You can check working example here.
Upvotes: 1