

{"id":113236,"date":"2023-05-24T09:00:16","date_gmt":"2023-05-24T03:30:16","guid":{"rendered":"https:\/\/data-flair.training\/blogs\/?p=113236"},"modified":"2023-05-24T12:11:38","modified_gmt":"2023-05-24T06:41:38","slug":"react-fragments","status":"publish","type":"post","link":"https:\/\/data-flair.training\/blogs\/react-fragments\/","title":{"rendered":"React Fragments"},"content":{"rendered":"<p>React Fragments were introduced as a way to group a list of children elements without creating a DOM element for that group. This is especially useful when you want to render a list of items without creating unnecessary markup.<\/p>\n<p>Before the introduction of React Fragments, developers had to wrap their list of children elements in a container element. This would add an extra DOM node to the rendered output, which was not always desired. With the introduction of React Fragments, developers can now group their list of children elements without creating this extra container element.<\/p>\n<h3>Using React Fragments<\/h3>\n<p>To use a React Fragment, you simply need to import it from the react package and then wrap your list of children elements with it. Here is an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">class MyForm extends React.Component {\r\n  constructor(props) {\r\n    super(props);\r\n    this.inputRef = React.createRef();\r\n  }\r\n\r\n  handleSubmit = (event) =&gt; {\r\n    event.preventDefault();\r\n    console.log(this.inputRef.current.value);\r\n  };\r\n\r\n  render() {\r\n    return (\r\n      &lt;form onSubmit={this.handleSubmit}&gt;\r\n        &lt;label&gt;\r\n          Name:\r\n          &lt;input type=\"text\" ref={this.inputRef} \/&gt;\r\n        &lt;\/label&gt;\r\n        &lt;button type=\"submit\"&gt;Submit&lt;\/button&gt;\r\n      &lt;\/form&gt;\r\n    );\r\n  }\r\n}\r\n\r\nReactDOM.render(&lt;MyForm \/&gt;, document.getElementById(\"root\"));\r\n<\/pre>\n<p><strong>Output<\/strong>:<\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-fragments.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-113537\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-fragments.png\" alt=\"react fragments\" width=\"450\" height=\"66\" \/><\/a><\/p>\n<p>In the example above, we are using the React.Fragment component to group our list of p elements. This will result in the expected output, but without the extra container element.<\/p>\n<h3>Uses of Fragments in React<\/h3>\n<p>Fragments are a feature in React that allow developers to group a list of children components. This can be useful in several scenarios, such as:<\/p>\n<p><strong>1. Avoiding extra markup:<\/strong><\/p>\n<p>In some cases, adding an additional parent element to group a list of components can result in unnecessary markup that may negatively impact performance.<br \/>\nFragments help avoid this issue by allowing developers to group the components without adding extra markup.<\/p>\n<p><strong>2. Improving readability:<\/strong><\/p>\n<p>When working with complex components that contain multiple child components.<br \/>\nUsing fragments can improve readability by clearly indicating which components are grouped together.<\/p>\n<p><strong>3. Avoiding layout issues:<\/strong><\/p>\n<p>When using certain layout components or libraries, such as CSS Grid or Flexbox, adding an additional parent element can sometimes interfere with the layout.<br \/>\nFragments help avoid this issue by allowing developers to group components without affecting the layout.<\/p>\n<h3>Benefits of Fragments in React<\/h3>\n<p><strong>1. Improved performance:<\/strong><\/p>\n<p>By using fragments, developers can avoid unnecessary DOM elements, resulting in faster rendering and improved performance. This is especially important when working with large or complex UIs.<\/p>\n<p><strong>2.<\/strong> <strong>Cleaner code:<\/strong><\/p>\n<p>Fragments can help make code more concise and readable by avoiding the need for additional wrapper elements. This can help reduce code bloat and make it easier to understand the structure of the component tree.<\/p>\n<p><strong>3. Better compatibility:<\/strong><\/p>\n<p>Fragments work seamlessly with other React features, such as portals and error boundaries. This can help ensure compatibility across different parts of a large codebase.<\/p>\n<p><strong>4. Improved accessibility:<\/strong><\/p>\n<p>When used appropriately, fragments can help improve accessibility by reducing the number of unnecessary elements in the DOM. This can make it easier for assistive technologies to navigate and understand the content of the page.<\/p>\n<p><strong>5. Simplified debugging:<\/strong><\/p>\n<p>By avoiding the need for additional wrapper elements, fragments can make it easier. This can save time and improve the efficiency of the development process.<\/p>\n<h3>Shorthand Syntax<\/h3>\n<p>There is also a shorthand syntax that can be used when using a React Fragment. Instead of using the React.Fragment component, you can use an empty tag &lt;&gt; and &lt;\/&gt; to wrap your list of children elements. Here is an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">function MyComponent() {\r\n  return (\r\n    &lt;&gt;\r\n      &lt;p&gt;Hi from DataFlair&lt;\/p&gt;\r\n      &lt;p&gt;Hi from React&lt;\/p&gt;\r\n      &lt;p&gt;Hi from the Writer&lt;\/p&gt;\r\n    &lt;\/&gt;\r\n  );\r\n}\r\n\r\nReactDOM.render(&lt;MyComponent \/&gt;, document.getElementById('root'));\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/shorthand.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-113538\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/shorthand.png\" alt=\"shorthand\" width=\"351\" height=\"170\" \/><\/a><\/p>\n<p>This example produces the same output as the previous example, but uses the shorthand syntax.<\/p>\n<h3>React Fragments with keys<\/h3>\n<p>React Fragments can also have keys, just like regular elements. This can be useful when rendering a list of elements that have a unique identifier. Here is an example:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\">import React from 'react';\r\n\r\nfunction MyComponent(props) {\r\n  return (\r\n    &lt;&gt;\r\n      {props.items.map(item =&gt; (\r\n        &lt;React.Fragment key={item.id}&gt;\r\n          &lt;h2&gt;{item.title}&lt;\/h2&gt;\r\n          &lt;p&gt;{item.description}&lt;\/p&gt;\r\n        &lt;\/React.Fragment&gt;\r\n      ))}\r\n    &lt;\/&gt;\r\n  );\r\n}\r\n\r\nconst items = [\r\n  { id: 1, title: 'Item 1', description: 'This is the first item' },\r\n  { id: 2, title: 'Item 2', description: 'This is the second item' },\r\n  { id: 3, title: 'Item 3', description: 'This is the third item' },\r\n];\r\n\r\nReactDOM.render(&lt;MyComponent items={items} \/&gt;, document.getElementById('root'));\r\n<\/pre>\n<p><strong>Output:<\/strong><\/p>\n<p><a href=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/fragments-with-keys.png\"><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter size-full wp-image-113539\" src=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/fragments-with-keys.png\" alt=\"fragments with keys\" width=\"379\" height=\"325\" \/><\/a><\/p>\n<p>In this example, we are rendering a list of items. Each item has a unique identifier, which we use as the key for the React Fragment. This can help with performance optimizations when updating the list of items.<\/p>\n<h3>Conclusion:<\/h3>\n<p>In conclusion, React Fragments are a way to group a list of children elements without creating a container element. They can be used with the React.Fragment component or the shorthand syntax &lt;&gt; and &lt;\/&gt;. They can also have keys, just like regular elements. Using React Fragments can help improve the readability and performance of your React components.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>React Fragments were introduced as a way to group a list of children elements without creating a DOM element for that group. This is especially useful when you want to render a list of&#46;&#46;&#46;<\/p>\n","protected":false},"author":581,"featured_media":113535,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[27227],"tags":[27421],"class_list":["post-113236","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-react-tutorials","tag-react-fragments"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.4 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>React Fragments - DataFlair<\/title>\n<meta name=\"description\" content=\"React Fragments are a way to group a list of children elements without creating a container element. Learn more with examples.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/data-flair.training\/blogs\/react-fragments\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"React Fragments - DataFlair\" \/>\n<meta property=\"og:description\" content=\"React Fragments are a way to group a list of children elements without creating a container element. Learn more with examples.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/data-flair.training\/blogs\/react-fragments\/\" \/>\n<meta property=\"og:site_name\" content=\"DataFlair\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/DataFlairWS\/\" \/>\n<meta property=\"article:published_time\" content=\"2023-05-24T03:30:16+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-05-24T06:41:38+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-fragments.webp\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"628\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/webp\" \/>\n<meta name=\"author\" content=\"DataFlair Team\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:site\" content=\"@DataFlairWS\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"DataFlair Team\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutes\" \/>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"React Fragments - DataFlair","description":"React Fragments are a way to group a list of children elements without creating a container element. Learn more with examples.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/data-flair.training\/blogs\/react-fragments\/","og_locale":"en_US","og_type":"article","og_title":"React Fragments - DataFlair","og_description":"React Fragments are a way to group a list of children elements without creating a container element. Learn more with examples.","og_url":"https:\/\/data-flair.training\/blogs\/react-fragments\/","og_site_name":"DataFlair","article_publisher":"https:\/\/www.facebook.com\/DataFlairWS\/","article_published_time":"2023-05-24T03:30:16+00:00","article_modified_time":"2023-05-24T06:41:38+00:00","og_image":[{"width":1200,"height":628,"url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-fragments.webp","type":"image\/webp"}],"author":"DataFlair Team","twitter_card":"summary_large_image","twitter_creator":"@DataFlairWS","twitter_site":"@DataFlairWS","twitter_misc":{"Written by":"DataFlair Team","Est. reading time":"5 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/data-flair.training\/blogs\/react-fragments\/#article","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/react-fragments\/"},"author":{"name":"DataFlair Team","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445"},"headline":"React Fragments","datePublished":"2023-05-24T03:30:16+00:00","dateModified":"2023-05-24T06:41:38+00:00","mainEntityOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/react-fragments\/"},"wordCount":658,"commentCount":0,"publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/react-fragments\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-fragments.webp","keywords":["React Fragments"],"articleSection":["React Tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/data-flair.training\/blogs\/react-fragments\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/data-flair.training\/blogs\/react-fragments\/","url":"https:\/\/data-flair.training\/blogs\/react-fragments\/","name":"React Fragments - DataFlair","isPartOf":{"@id":"https:\/\/data-flair.training\/blogs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/data-flair.training\/blogs\/react-fragments\/#primaryimage"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/react-fragments\/#primaryimage"},"thumbnailUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-fragments.webp","datePublished":"2023-05-24T03:30:16+00:00","dateModified":"2023-05-24T06:41:38+00:00","description":"React Fragments are a way to group a list of children elements without creating a container element. Learn more with examples.","breadcrumb":{"@id":"https:\/\/data-flair.training\/blogs\/react-fragments\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/data-flair.training\/blogs\/react-fragments\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/react-fragments\/#primaryimage","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-fragments.webp","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2023\/03\/react-fragments.webp","width":1200,"height":628,"caption":"react fragments"},{"@type":"BreadcrumbList","@id":"https:\/\/data-flair.training\/blogs\/react-fragments\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Blog Home","item":"https:\/\/data-flair.training\/blogs\/"},{"@type":"ListItem","position":2,"name":"React Tutorials","item":"https:\/\/data-flair.training\/blogs\/category\/react-tutorials\/"},{"@type":"ListItem","position":3,"name":"React Fragments"}]},{"@type":"WebSite","@id":"https:\/\/data-flair.training\/blogs\/#website","url":"https:\/\/data-flair.training\/blogs\/","name":"DataFlair","description":"Learn Today. Lead Tomorrow.","publisher":{"@id":"https:\/\/data-flair.training\/blogs\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/data-flair.training\/blogs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/data-flair.training\/blogs\/#organization","name":"DataFlair","url":"https:\/\/data-flair.training\/blogs\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/","url":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","contentUrl":"https:\/\/data-flair.training\/blogs\/wp-content\/uploads\/sites\/2\/2016\/07\/Data-Flair.png","width":106,"height":48,"caption":"DataFlair"},"image":{"@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/DataFlairWS\/","https:\/\/x.com\/DataFlairWS","https:\/\/www.linkedin.com\/company\/dataflair-web-services-pvt-ltd\/","https:\/\/www.youtube.com\/user\/DataFlairWS"]},{"@type":"Person","@id":"https:\/\/data-flair.training\/blogs\/#\/schema\/person\/c187795dc82ab948373cca526df7c445","name":"DataFlair Team","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/2302ebc438084d2f1f993edc1996a0aae01332e81f3227cba8df0c48ec010ca4?s=96&d=mm&r=g","caption":"DataFlair Team"},"description":"DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.","url":"https:\/\/data-flair.training\/blogs\/author\/dfteam6\/"}]}},"amp_enabled":true,"_links":{"self":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113236","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/users\/581"}],"replies":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/comments?post=113236"}],"version-history":[{"count":5,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113236\/revisions"}],"predecessor-version":[{"id":113540,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/posts\/113236\/revisions\/113540"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media\/113535"}],"wp:attachment":[{"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/media?parent=113236"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/categories?post=113236"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/data-flair.training\/blogs\/wp-json\/wp\/v2\/tags?post=113236"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}