DEV Community

Cover image for 🗄️ Create own React.Fragment
Andrei L
Andrei L

Posted on • Edited on

🗄️ Create own React.Fragment

Do you want to use React.Fragment in your app?
Are you using a React version lower than 16.2 that does not support fragments?
For some reason you cannot update React to support it?

Well I can tell you that you can create your own Fragment!

function Fragment(props) {
  return props.children;
}
Enter fullscreen mode Exit fullscreen mode

Yeap is that simple.

import React from 'react';
import ReactDOM from 'react-dom';

function Fragment(props) {
  return props.children;
}

function App() {
  return (
    <Fragment>
      <div>We</div>
      <div>have</div>
      <div>own</div>
      <div>Fragments</div>
      <div>!!!</div>
    </Fragment>  
  )
}

ReactDOM.render(<App />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

Here is a demo if you want to play around.

Note that React 16.1 is used that does not support Fragment

Also if you take a look at Preact Fragment implementation, you will see exactly the function that we wrote above.

https://github.com/preactjs/preact/blob/da382e13d9377a53056e4cb0fd741f6e0aadf1c1/src/create-element.js#L92-L94

Cover Photo by Dominik Scythe on Unsplash

Top comments (2)

Collapse
 
fasani profile image
Michael Fasani

Very cool! <3

Collapse
 
iamandrewluca profile image
Andrei L

Thank you Sir Michael :)