Guillermo Quiros
Guillermo Quiros

Reputation: 441

React returning multiple element without creating a container element

Is there a way in react to return multiple elements without creating a extra element that contain the children? So I can write a function as follow:

function renderRows(){
return (
   <div className="row">Row1</div>
   <div className="row">Row1</div>
   <div className="row">Row1</div>)
}

Upvotes: 0

Views: 51

Answers (2)

kiranvj
kiranvj

Reputation: 34107

You can use Fragments for this.

render() {
  return (
    <React.Fragment>
      <div className="row">Row1</div>
      <div className="row">Row1</div>
      <div className="row">Row1</div>
    </React.Fragment>
  );
}

There is also a shorthand syntax for this <></>, but its not supported in all tools. Try it

render() {
  return (
    <>
      <div className="row">Row1</div>
      <div className="row">Row1</div>
      <div className="row">Row1</div>
    </>
  );
}

Check the live demo here

Upvotes: 1

Ronze
Ronze

Reputation: 1574

You can use React.Fragment like this:

import React, { Fragment } from 'react';

... 

render() { 
  return(
    <Fragment>
      <div></div>
      <div></div>
    </Fragment>
 )
}

Upvotes: 1

Related Questions