What is a Fragment?
The React.Fragment
component allows you to return multiple elements in a render()
method without creating an additional DOM element.
If you are thinking about where React.Fragment
component is useful then letβs take a scenario where you what to print two span
side by side without wrapping it by an additional element such as div
tag then this case you can use React.Fragment
component.
We are not using JSX in the code given below.
<body>
<div id="root">This will be replace by React</div>
<script src="https://unpkg.com/react@16.13.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script>
<script type="text/babel">
const rootElement = document.getElementById("root");
const helloElement = React.createElement("span", null, "Hello, ");
const worldElement = React.createElement("span", null, "World");
const fragment = React.createElement(
React.Fragment,
null,
helloElement,
worldElement
);
ReactDOM.render(fragment, rootElement);
</script>
</body>
JSX Code:
<body>
<div id="root">This will be replace by React</div>
<script src="https://unpkg.com/react@16.13.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script>
<script type="text/babel">
const rootElement = document.getElementById("root");
// JSX Code
const helloElement = <span>Hello, </span>;
const worldElement = <span>World</span>;
const fragment = (
<React.Fragment>
{helloElement}
{worldElement}
</React.Fragment>
);
ReactDOM.render(fragment, rootElement);
</script>
</body>
You can also use <></>
syntax instead of React.Fragment
which is I personly use.
JSX Code:
<body>
<div id="root">This will be replace by React</div>
<script src="https://unpkg.com/react@16.13.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.13.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.9.4/babel.js"></script>
<script type="text/babel">
const rootElement = document.getElementById("root");
// JSX Code
const helloElement = <span>Hello, </span>;
const worldElement = <span>World</span>;
const fragment = (
<>
{helloElement}
{worldElement}
</>
);
ReactDOM.render(fragment, rootElement);
</script>
</body>
Top comments (2)
Great post! Will be very helpful for all the beginners out there.
thankyou so much π, please let me know what can I do more to make this series more beneficial π₯