React Fragments
Did you ever wonder how to return multiple components/elements from render() method without wrapping it in a parent component or creating an extra DOM element?
Yes, React does support this kind. But you still need to wrap it in a dummy DOM element created by REACT called fragment. Below is the code how to use it.
render() {
return (
<React.Fragment> // this is the dummy element you need to use.
Some text.
<h2>A heading</h2>
</React.Fragment>
);
}
The above code creates dom elements like below.
Some text.
<h2>A heading</h2>
Your elements are not wrapped inside any other DOM elements. It seems you need to do more keystrokes. That you have to type <React.Fragment> </React.Fragment>. Don't worry, from REACT V16.2 they've introduced a short form of the same.
render() {
return (
<> // this is equal to React.Fragment
Some text.
<h2>A heading</h2>
</>
);
}
You can't use this Fragment syntax as other DOM elements like div, span, etc. Remember it will not create any extra DOM Element, so you can't apply styles on this element. You cannot pass any kind of props to it.
The only prop that you can pass is key while you are iterating an array. One more thing to remember you cannot use the key prop while you are using the short notation.
Read the official documentation of <React.Fragment> from the below link.
Akhil, Hi! We, ADFAR Tech require 10 Senior React Native Tech Leads (OFFSHORE). -10+ years of exp. - Banking & finance domain exp. - Team & Tech Lead with end of end project exp. If you wish to partner with us, please WhatsApp. Regards, Pankti | ADFAR Tech +966 59 49 72 620