I am new in ReactJs. I have code below:
{users.map((user, index) => (
<tr key={user.id}>
<td>{ index 1 }</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.gender}</td>
<td>{user.status}</td>
</tr>
))}
My question is how to add if condition in the code, e.g:
if (user.status) == "0"
return "In-Active"
else if (user.status) == "1"
return "Active"
else if (user.status) == "2"
return "Disabled"
CodePudding user response:
Just wrap it in a function:
function getStatusLabel(status) {
if (user.status) == "0"
return "In-Active"
else if (user.status) == "1"
return "Active"
else if (user.status) == "2"
return "Disabled"
}
users.map((user, index) => (
<tr key={user.id}>
<td>{ index 1 }</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.gender}</td>
<td>{getStatusLabel(user.status)}</td>
</tr>
))}
CodePudding user response:
Simply create an object for status
:
const status = {
'0':'In-Active',
'1':'Active',
'2':'Disabled'
}
{users.map((user, index) => (
<tr key={user.id}>
<td>{ index 1 }</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.gender}</td>
<td>{status[user.status]}</td>
</tr>
))}
CodePudding user response:
Hey @John you can achieve this by adding third row-
{users.map((user, index) => (
<tr key={user.id}>
<td>{ index 1 }</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.gender}</td>
<td>{user.status}</td>
<td>{user.status == "0"? "In-Active": user.status =="1"? "Active":"Disabled"}</td>
</tr>
))}
Hope this solution will solve your query, if you still facing issue, just lemme know, i will help you. thanks
CodePudding user response:
you can create a method and check user status on there
function renderuserStatus(user) {
if (user.status) == "0"
return "In-Active"
else if (user.status) == "1"
return "Active"
else if (user.status) == "2"
return "Disabled"
}
{users.map((user, index) => (
<tr key={user.id}>
<td>{ index 1 }</td>
<td>{user.name}</td>
<td>{user.email}</td>
<td>{user.gender}</td>
<td>{renderuserStatus(user)}</td>
</tr>
))}