0

I've added some piece of code in render method of react using conditional (ternary) operator. The thing is the condition is rendered true also the control goes into the block. But when I print the value the variable is undefined

I tried inserting an alert inside the block to check if the control traverses the block and it worked.

const comments =
      details.comments_count >= 1
        ? Object.keys(details.comments_list).forEach(keys => {           
            return (
              <ListItem
                alignItems="flex-start"
                key={details.comments_list[keys].aid}
              >
                <ListItemAvatar>
                  <Avatar>{details.comments_list[keys].aname.charAt(0)}</Avatar>
                </ListItemAvatar>
                <Card style={useStyles.card}>
                  <CardContent>
                    <ListItemText
                      primary={details.comments_list[keys].aname}
                      secondary={details.comments_list[keys].content}
                    />
                  </CardContent>
                </Card>
              </ListItem>
            );
          })
        : null;

console.log(comments);
//=>undefined

I don't actually know why this this is happening, given the result of conditional expression is true. Any help is appreciated. Thanks.

1
  • 1
    Array.prototype.forEach returns undefined. So you get exactly what you implemented. Commented Aug 19, 2019 at 5:34

1 Answer 1

3

forEach won't return anything but undefined. You need to use map.

const comments =
      details.comments_count >= 1
        ? Object.keys(details.comments_list).map(keys => {           
            return (
              <ListItem
                alignItems="flex-start"
                key={details.comments_list[keys].aid}
              >
                <ListItemAvatar>
                  <Avatar>{details.comments_list[keys].aname.charAt(0)}</Avatar>
                </ListItemAvatar>
                <Card style={useStyles.card}>
                  <CardContent>
                    <ListItemText
                      primary={details.comments_list[keys].aname}
                      secondary={details.comments_list[keys].content}
                    />
                  </CardContent>
                </Card>
              </ListItem>
            );
          })
        : null;

console.log(comments);
Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm, never knew forEach returns undefined. Thanks @ravibagul91

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.