'React Native what exactly is the <> (empty) component
In React Native you can encapsulate a set of components in one single <View>
(or similar) component. You can also encapsulate a set of components as <>
and </>
. What are these? Do they just translate to an base View? It's probably not a good practice but it doesn't give a warning and it doesn't crash.
Solution 1:[1]
It's the React shortcut for Fragment
component.
You can write like this :
import React, { Component } from 'react'
class Component extends Component {
render() {
return <> <ComponentA/> <ComponentB/> </>
}
}
Or without the shortcut and import Fragment
component
import React, { Component, Fragment } from 'react'
class Component extends Component {
render() {
return <Fragment> <ComponentA/> <ComponentB/> </Fragment>
}
}
You have to know, you can't use any key or prop with the shortcut syntax.
Here's the official documentation
I hope it helps !
Solution 2:[2]
In addition to what He has said, it is used to embed many HTMLElements that you don't what them to be nested into a <div>
for example.
For example, you may have this use cases
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
For more explanation you can read this React Official Documentation Fragment
Solution 3:[3]
In react <> and </>
is just a syntactic sugar for <React.Fragment>
. What it basically means is all components should be wrapped in a parent element. So without disturbing the whole schematic design <> provides a wrapper to wrap all your elemnts inside it .
<React.Fragment>
// your code
</React.Fragment>
is same as
<>
// your code
</>
hope it helps
Solution 4:[4]
One of the highlights of React v16.2 is Fragments.
If you're working with React projects, you may be familiar with wrapping your child components with <div>
or <span>
in your render().
Fragment is a first-class component that you can use to wrap your child components and elements in place of <div>
or <span>
tags. Like so,
render(){
return(
<Fragment>
<h2>Heading</h2>
<ChildA />
</Fragment>
);
}
or
render(){
return(
<React.Fragment>
<h2>Heading</h2>
<ChildA />
</React.Fragment>
);
}
As a shortcut, you can also use empty tags <></>
to indicate a fragment. Like so,
render(){
return(
<>
<h2>Heading</h2>
<ChildA />
</>
);
}
Solution 5:[5]
If you dont want to put extra divs & spans
,
<></> will be nice pick for you
React does the replacement of React.Fragment
component there
<></> == <React.Fragment></React.Fragment>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Patrissol Kenfack |
Solution 3 | WangYudong |
Solution 4 | Dharman |
Solution 5 | Asd |