0

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"


              
1
  • You may wrap your status texts in an object like let statusTexts = { "0": "In-Active", "1": "Active", "2": "Disabled" }, then can render as <td>{statusTexts[user.status]}</td> Commented Oct 29, 2022 at 12:22

4 Answers 4

2

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> 
))}
Sign up to request clarification or add additional context in comments.

Comments

2

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> 
))}

Comments

0

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

Comments

0

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> 
))}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.