🗄️ Create own React.Fragment

Fragments are one of those React features you miss the moment you can’t have them. If you’re stuck on a React version older than 16.2 and can’t upgrade, you might think you’re out of luck. You’re not, and the way out is smaller than you’d expect.

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

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

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"));

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

Created At
8/16/2018
Updated At
10/11/2021
Published At
9/17/2018