Codecademy Forums

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>
  );
}
10 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>;
  }
}
3 Likes

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.

1 Like

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!

1 Like