Kai021195
Kai021195

Reputation: 833

jsx map inside if else condition

I have a condition look like below

{finishedTodos
? 
                <ListItem button divider className={classes.finishCategory} >
                <ArrowForward className={classes.checkIcon} />
                <ListItemText primary={`Finished      ${finishedTodos.length}`}  style={{color:"tomato"}}/>
                </ListItem>
                
: null }
//---------------------------------------------
        {finishedTodos.map((todo) =>(     
              <ListItem button divider>
                <CheckCircle className={classes.checkIcon} />
                <ListItemText primary={todo.title} style={{textDecoration:"line-through",color:"gray"}} />
              </ListItem>
        ))}

so right now what I want to do is I Want to combine these two , and when I tried to put {finishedTodos.map... below the </ListItem>,it reported ": expected" , so I think there's something wrong with formatting , do anyone know how to solve this ?

Upvotes: 0

Views: 59

Answers (2)

Remy Smith
Remy Smith

Reputation: 126

JSX requires returned code blocks to be wrapped in a single JSX element, like a <div>. You can also use simple JSX fragments <>...</> to wrap your code.

In this case, I would also recommend using a short circuit operator, &&, instead of a ternary operator ? ... :null for simple if {} statements.

{finishedTodos  &&
  <>
    <ListItem button divider className={classes.finishCategory} >
       <ArrowForward className={classes.checkIcon} />
       <ListItemText 
          primary={`Finished ${finishedTodos.length}`}  
          style={{color:"tomato"}}/>
    </ListItem>
    {finishedTodos.map((todo) => 
       <ListItem button divider>
          <CheckCircle className={classes.checkIcon} />
          <ListItemText 
             primary={todo.title} 
             style={{textDecoration:"line-through",color:"gray"}} />
       </ListItem>
     )}
  </>
}

Upvotes: 3

Viet
Viet

Reputation: 12777

Just update like it with Fragment

{
  finishedTodos ? (
    <>
      <ListItem button divider className={classes.finishCategory}>
        <ArrowForward className={classes.checkIcon} />
        <ListItemText
          primary={`Finished      ${finishedTodos.length}`}
          style={{ color: "tomato" }}
        />
      </ListItem>
      {finishedTodos.map((todo) => (
        <ListItem button divider>
          <CheckCircle className={classes.checkIcon} />
          <ListItemText
            primary={todo.title}
            style={{ textDecoration: "line-through", color: "gray" }}
          />
        </ListItem>
      ))}
    </>
  ) : null;
}

Upvotes: 2

Related Questions