Functional component and return statement in ReactJS

Viewed 90

I'm getting a weird error of unreachable code detected in the return statement of ReactJS.

In the code snippet given below, the error is shown at the div with the button component.

How can I resolve this issue?

function RenderComments({ comments }) {
    return (
        comments.map((comment) =>
            <div>
                <ul className="list-unstyled">
                    <li className='font-quote'>{comment.comment}</li>
                </ul>
                <ul className="list-unstyled">
                    <li className='font-author'>--{comment.author}, {comment.date}</li>
                </ul>
            </div>
        )
        <div className = "row m-1" >
            <Button type="submit" value="submit"><i className="fa fa-pencil"></i> Submit Comment</Button>
        </div>   
    );
}   
3 Answers

The div containing the Button is not reachable, you should wrap both in a grouping tag, a fragment for example:

function RenderComments({ comments }) {
  return (
    <>
      {comments.map((comment) => (
        <div>
          <ul className="list-unstyled">
            <li className="font-quote">{comment.comment}</li>
          </ul>
          <ul className="list-unstyled">
            <li className="font-author">
              --{comment.author}, {comment.date}
            </li>
          </ul>
        </div>
      ))}
      <div className="row m-1">
        <Button type="submit" value="submit">
          <i className="fa fa-pencil"></i> Submit Comment
        </Button>
      </div>
    </>
  );
}

That's an invalid code... You're out of the return statement you're using row m-1.

You need to use <></> fragments to return two or more elements:

function RenderComments({ comments }) {
  return (
    <>
      {comments.map((comment) => (
        <div>
          <ul className="list-unstyled">
            <li className="font-quote">{comment.comment}</li>
          </ul>
          <ul className="list-unstyled">
            <li className="font-author">
              --{comment.author}, {comment.date}
            </li>
          </ul>
        </div>
      ))}

      <div className="row m-1">
        <Button type="submit" value="submit">
          <i className="fa fa-pencil"></i> Submit Comment
        </Button>
      </div>
    </>
  );
}
function RenderComments({ comments }) {
  return (
    <>
      {comments.map((comment) => (
        <div>
          <ul className="list-unstyled">
            <li className="font-quote">{comment.comment}</li>
          </ul>
          <ul className="list-unstyled">
            <li className="font-author">
              --{comment.author}, {comment.date}
            </li>
          </ul>
        </div>
      ))}

      <div className="row m-1">
        <Button type="submit" value="submit">
          <i className="fa fa-pencil"></i> Submit Comment
        </Button>
      </div>
    </>
  );
}
Related