EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

React Fragment

By Rahul DubeyRahul Dubey

Home » Software Development » Software Development Tutorials » React Native Tutorial » React Fragment

React Fragment

Introduction to React Fragment

React Fragments were first launched in the version React 16.2.0. These are used where, earlier the developers were using wrapper div as React Fragments help us in grouping a set of children without the need to add additional nodes to the DOM. Earlier for returning multiple elements, the elements were wrapped in a div. This led to some irrelevant markup or rendering of irrelevant HTML which was not good for the website. This problem was solved by React Fragments. This easily returns multiple elements without the need of wrapper div. In this article, we will understand how to use this with some examples.

Syntax:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

render() {
return (
<React.Fragment>
<ElementA />
<ElementB />
<ElementC />
</React.Fragment>
);
}

How does React Fragment work with Examples?

Below are the examples of the sample to know to how it works:

1. Short Example

Components inside src folder:

  • index.js
  • style.css

index.js

import React from 'react'
import ReactDOM from 'react-dom'
function App() {
return (
<>
<React.Fragment key="test">
<h1>Welcome to Awesome world of EDUCBA</h1>
<h2>Kindly visit our website "https://www.educba.com/" for best online trainings and video courses.</h2>
</React.Fragment>
</>
)
}
ReactDOM.render(<App />, document.getElementById('root'))

styles.css

.App {
font-family: 'Times New Roman', Times, serif, sans-serif;
text-align: center;
}

Output:

Welcome to Educba

2. Basic

Components inside src folder:

  • index.js

index.js

import React
, { Component
, Fragment } from "react";
import { render } from "react-dom";
class Columns extends Component {
render() {
const heros = [
{ name: 'Dr. Strange', id: 1 },
{ name: 'Ironman', id: 2 },
{ name: 'Rocket', id: 3 }
];
return (
<ul>
{heros.map(hero => (
<Fragment key={hero.id
}>
{hero.name
} is SUPER AMAZING!!....
</Fragment>
))}
</ul>
);
}
}
class Table extends Component {
render() {
return (
<table>
<tr>
<Columns />
</tr>
</table>
);
}
}
render(<Table />, document.getElementById("root"));

Output:

React Fragment - 2

3. With SignIn and SignOut buttons

Components inside src folder:

  • config folder
  • admin.js
  • home.js
  • login.js
  • index.js

Components inside config folder:

  • switch.js
  • routes.js

Switch.js

import { Switch } from "react-router-dom";
import React
, { Fragment } from "react";
export default function FragmentSupportingSwitch({ children }) {
const flattenedChildren = [];
flatten(flattenedChildren, children);
return React.createElement.apply(
React,
[Switch, null].concat(flattenedChildren)
);
}
function flatten(target, children) {
React.Children.forEach(children, child => {
if (React.isValidElement(child)) {
if (child.type === Fragment) {
flatten(target, child.props.children);
} else {
target.push(child);
}
}
});
}

routes.js

import React
, { Fragment } from "react";
import { Router
, Route } from "react-router-dom";
import Switch from "./Switch";
import createBrowserHistory from "history/createBrowserHistory";
import Login from "../Login";
import Home from "../Home";
import Admin from "../Admin";
export const history = createBrowserHistory();
const Routes = ({ isLoggedIn, login, logout }) => {
return (
<Router history={history}>
<Switch>
{!isLoggedIn && (
<Fragment>
<Route path="/" component={() => <Login login={login} />} />
</Fragment>
)}
) : (
<Fragment>
<Route exact path="/" component={() => <Home logout={logout} />} />
<Route
exact
path="/admin"
component={() => <Admin history={history} logout={logout} />}
/>
</Fragment>
)}
<Route path="*" component={() => <div>Address Not Found</div>} />
</Switch>
</Router>
);
};
export default Routes;

Popular Course in this category
All in One Software Development Bundle (600+ Courses, 50+ projects)600+ Online Courses | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (3,144 ratings)
Course Price

View Course

Related Courses

Admin.js

import React from "react";
export default ({ logout, history }) => (
<div>
<h1>Welcome to Admin Page</h1>
<button onClick={() => history.goBack()}>Click to Go Back to Previous Menu</button>
</div>
);

Home.js

import React from "react";
import { Link } from "react-router-dom";
export default ({ logout }) => (
<div>
<h1>Welcome to Home Page</h1>
<Link to="/admin">Click to Go To Admin Page</Link>
<br />
<button onClick={() => logout()}>Signout</button>
</div>
);

Login.js

import React from "react";
export default ({ login }) => (
<div>
<h1>Welcome to SignIn Page</h1>
<button onClick={() => login()}>Click to SignIn
</button>
</div>
);

index.js

import React from "react";
import { render } from "react-dom";
import Routes from "./config/routes";
class App extends React.Component {
state = {
isLoggedIn: false
};
login = () => {
this.setState({ isLoggedIn: true });
};
logout = () => {
this.setState({ isLoggedIn: false });
};
render() {
return (
<div>
<Routes
login={this.login}
logout={this.logout}
isLoggedIn={this.state.isLoggedIn}
/>
</div>
);
}
}
render(<App />, document.getElementById("root"));

Output:

React Fragment - 3

SignOut buttons

4. With Switch

Components inside src folder:

  • index.js

index.js

import React from "react";
import ReactDOM from "react-dom";
import {
Switch as BaseSwitch
, Route
, BrowserRouter
, Link
} from "react-router-dom";
import flattenChildren from "react-flatten-children";
const Switch = ({ children }) => (
<BaseSwitch>{flattenChildren(children)}</BaseSwitch>
);
class App extends React.Component {
state = { private: false };
render() {
return (
<BrowserRouter>
<React.Fragment>
<button
type="button"
onClick={() => this.setState(s => ({ private: !s.private }))}
>
{this.state.private ? "Sign Out" : "Sign In"}
</button>
<nav>
<ul>
<li>
<Link to="/">Home Screen</Link>
</li>
<li>
<Link to="/about">About Us</Link>
</li>
{this.state.private && (
<React.Fragment>
<li>
<Link to="/account">My Account</Link>
</li>
<li>
<Link to="/support">Contact Us</Link>
</li>
</React.Fragment>
)}
</ul>
</nav>
<Switch>
<Route exact path="/" render={() => "Welcome to Home Screen"} />
<Route path="/about" render={() => "Information About Us"} />
{this.state.private && (
<React.Fragment>
<Route path="/account" render={() => "My Account Screen"} />
<Route path="/support" render={() => "Contact Us through below modes"} />
</React.Fragment>
)}
</Switch>
</React.Fragment>
</BrowserRouter>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Output:

React Fragment - 5

Switch

React Fragment - 7

5. With Render Fragment

Files to develop this:

  • fragment.js
  • Hello.js
  • index.html
  • index.js

Fragment.js

import React from 'react';
import PropTypes from 'prop-types';
const [reactMajorVersion] = React.version.split('.');
const canReturnArray = parseInt(reactMajorVersion, 10) >= 16;
const RenderArrayOrDiv = ({ children, as: Wrapper, ...others }) => (
Wrapper
? <Wrapper {...others}>{children}</Wrapper>
: React.Children.toArray(children)
);
if (process.env.NODE_ENV !== 'production') {
RenderArrayOrDiv.propTypes = {
as: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
children: PropTypes.node.isRequired,
};
}
RenderArrayOrDiv.defaultProps = {
as: canReturnArray ? undefined : 'div',
};
console.log(React.Fragment);
const Fragment = React.Fragment ? React.Fragment : RenderArrayOrDiv;
console.log(Fragment);
export default Fragment;

Hello.js

import React from 'react';
export default ({ name }) => <h1>Hello! {name}!</h1>;

index.html

<div id="root"></div>

index.js

import React from 'react';
import { render } from 'react-dom';
import Fragment from 'render-fragment';
import Hello from './Hello';
const App = () => (
<Fragment>
<h1>{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}{'\u2724'}</h1>
<Hello name="Welcome to Our Website" />
<h2>{'\u2729'}Start watching training videos and see magic happen {'\u2729'}</h2>
<h3> {'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}{'\u2728'}</h3>
<h4>{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}{'\u2726'}</h4>
</Fragment>
);
render(<App />, document.getElementById('root'));

Output:

Render Fragment

Conclusion

In this article, we understood about This and the reason it is so helpful to the developers. We went through five different examples to understand the different ways to use this same. This is easy to use and I hope this article would have explained the ways to use it in a simple and meaningful way.

Recommended Articles

This is a guide to React Fragment. Here we discuss how does it work with examples to implement React Fragment. You can also go through our other related articles to learn more –

  1. React Native Local Storage
  2. React Native Libraries
  3. React Components Libraries
  4. React Native Components

All in One Software Development Bundle (600+ Courses, 50+ projects)

600+ Online Courses

3000+ Hours

Verifiable Certificates

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
React Native Tutorial
  • Basic
    • What is React Native?
    • React Versions
    • React Constructor
    • React Native Architecture
    • React Native Libraries
    • React Components Libraries
    • React Native Components
    • React Component Library
    • React Component Lifecycle
    • React Native Framework
    • React Higher Order Component
    • React Ternary Operator
    • React Native Charts
    • React Native Layout
    • React Native Grid
    • React Native Fetch
    • React Native Modal
    • React Native SVG
    • Button in React Native
    • React List Components
    • React Native Element
    • React Native FlatList
    • React Native SectionList
    • react native dropdown
    • React Native Menu
    • React Native State
    • React State Management
    • React Native Tabs
    • React Native Tab Bar
    • React Format
    • React-Native Switch
    • React Native Firebase
    • React Native Flexbox
    • React Native StatusBar
    • React Native ScrollView
    • React Native ListView
    • React Native TextInput
    • React Native Table
    • React-Native Border Style
    • React Native Search Bar
    • React-Native StyleSheet
    • React Native Vector Icons
    • React Native Login Screen
    • React Native Splash Screen
    • React Native Image Picker
    • React Native Navigation
    • React Native Swift
    • React Controlled Input
    • React Fragment
    • React Native Color
    • React Portals
    • React Refs
    • React shouldComponentUpdate()
    • React ComponentDidMount()
    • React componentWillUpdate()
    • React Native Orientation
    • React Native Animation
    • React Native Form
    • React Props
    • React Native Linear Gradient
    • React Native AsyncStorage
    • React Error Boundaries
    • React Native Progress Bar
    • React-Native Calendar
    • React Native Linking
    • React Native DatePicker
    • React Native Image
    • React Native Drawer
    • React Native Drawer Navigation
    • React Native Fonts
    • React Native Overlay
    • React Native OneSignal
    • React Native Template
    • React Native Router
    • React Router Transition
    • React Dispatcher
    • React Native Redux
    • React JSX
    • React native keyboardavoidingview
    • React Native Permissions
    • React Redux Connect
    • React Native Material
    • React Native Gesture Handler
    • React Native Theme
    • React Native Accessibility
    • React Native Justify Content
    • MobX React Native
    • React Native Authentication
    • React Native UUID
    • React Native Geolocation
    • React Native Debugger
    • React Native Carousel
    • React Native Local Storage
    • React Native TypeScript
    • React Bootstrap
    • React Native SQLite
    • React Native Interview Questions
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - All in One Software Development Bundle (600+ Courses, 50+ projects) Learn More