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:
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:
2. Basic
Components inside src folder:
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:
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;
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:
4. With Switch
Components inside src folder:
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:
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:
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 the introduction, syntax and working of React Fragment along with examples and code. You can also go through our other related articles to learn more –