- Views: 1
- Report Article
- Articles
- Computers
- Programming
Fragments in ReactJS(v.16.2.0)
![Author: Sasi Kiran](/inc/images/no-person-100.gif)
Posted: Mar 21, 2021
The fragment is a first-class component to wrap your child components and HTML elements instead of using any HTML element.
Normal way of wrapping child component in render method
render(){ return( Without Fragment ); }For above example, if you will not wrap the child component using tag then you would face syntax error that the JSX element must be rendered in an enclosing tag.To understand this, Let’s think about function call, when we call the function, we can’t return more than once at a time in a function call, and we can return nothing also. So its necessary to wrap child component in an enclosing tag.
To solve above problem, React 16.0 launched a new feature for returning an array of elements from a component’s render method. Instead of wrapping the children in a DOM element, you can put them into an array. Here you can see above example
render() { return [ A heading Element, "String Element", Another heading Element, ]; }But while we will use this feature we need to keep in mind few points like
- Children in an array must be separated by commas.
- Children in an array must have a key to prevent React’s key warning.
- Strings must be wrapped in quotes.
Using above approach or returning array of the element increases complexity so to make things consistent latest version of React, React v.16.2.0 has been launched the feature called Fragment. So according to the previous example in every component, we need to wrap child component in an enclosing tag like or. So if we think about whole application then we may add a lot of extra tags which will make our DOM operation expensive by adding an extra node. Using this feature of ReactJS Fragment now we can return child component without adding an extra node to the DOM.
Fragment’s way of wrapping the child component in render method
render(){ return( With Fragment ); }We can also use empty tags instead of
render(){ return( With Fragment ); }But if we have to pass any attribute then we can’t use the empty tags to wrap child component. Then we have to use tags to wrap child component and to pass attributes.
render(){ return( {props.list.map(item =>( {item.name} {item.description} ))} ); }Looking for ReactJS Development Services, hire our dedicated developers!
About the Author
My sef sasi kiran, working as an digital marketer
Rate this Article
Leave a Comment
![Author Thumbnail](/inc/images/no-person-100.gif)