Can we return multiple elements in the render function?

Question

In the context of this exercise, can we return multiple elements in the render function?

Answer

Yes, you can return more than one element in the render function.

In previous versions of React, if you wanted to do so, you had to wrap them inside another element, such as a <div> element. For example, you would have to do something like the following,

render() {
  return (
    <div>
      <Element1 />
      <Element2 />
    </div>
  );
}   

However, the downside is that this added another element to the DOM, even if you did not want to add the <div> element.

In the current versions, you can utilize what is known as a React.Fragment, which lets you return multiple elements without the need to create a wrapper element. It would look like the following,

render() {
  return (
    <React.Fragment>
      <Element1 />
      <Element2 />
    </React.Fragment>
  );
}
14 Likes

Can we use return twice in the same render function?

class MyComponentClass extends React.Component {
  render() {
    return <h1>Hello world</h1>;
    return <b>This is a second paragraph.</b>;
  }
}
1 Like

I pretty sure you can’t. The reason you can’t have multiple return statements is because once a function or a class reaches a return statement, it return the value and exits the function, class.

14 Likes

There are currently two ways:

Old version of React:

render() {
  return (
    <div>
      <Element1 />
      <Element2 />
    </div>
  );
}  

New Version of React

render() {
  return (
    <React.Fragment>
      <Element1 />
      <Element2 />
    </React.Fragment>
  );
}

Both versions works currently, the second version prevents that you add a new <div> to the DOM if you don’t wish to do so. I hope that helps!

8 Likes

There is a new, shorter syntax you can use for declaring fragments. It looks like empty tags:

class Columns extends React.Component {
  render() {
    return (
      <>
        <td>Hello</td>
        <td>World</td>
      </>
    );
  }
}

You can use <></> the same way you’d use any other element except that it doesn’t support keys or attributes.

18 Likes

noelbray is correct, the second return statement would be ignored.

Will the empty tags create a DOM element?

No,

in the sense that the empty tags will not result in an additional DOM element over and above the elements enclosed within the empty tags.

2 Likes

No, it won’t,that is the point of the new update

1 Like

I`m just getting started with React, but I was pretty sure the answer to this question would be “No”.

Isn’t this “feature” a violation of the concept of Component?

As others have stated, once you reach a return statement your code will exit the function, which means that the function can only execute one return statement. However, if you use a conditional statement to choose between which return statement gets executed, you could have more than one in the function.