Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native - what is the different <View> or <>?

Are there any differences between and <> </>?

When using I have to import the 'react-native' package

import { View } from 'react-native'

no when using <> </>

<View>
 <FirstComponent/>
 <SeconComponent/>
</View>
<>
 <FirstComponent/>
 <SeconComponent/>
</>

they are similar?

like image 781
fabio87 Avatar asked Sep 18 '25 22:09

fabio87


2 Answers

They are not. View is a component that can be counted as an element while <> also known as Fragment, act like a wrapper but it's not an element.

<View style={{flexDirection: 'row', justifyContent: 'space-between' }}>
  <View>
    <FirstComponent />
    <SecondComponent />
  </View>
</View>

For the code above, you will see SecondComponent directly beside FirstComponent

<View style={{flexDirection: 'row', justifyContent: 'space-between' }}>
  <>
    <FirstComponent />
    <SecondComponent />
  </>
</View>

For the example above, you will see a big gap between FirstComponent and SecondComponent.

Fragment is often being used because you want to logically group the elements together but don't want to mess up the styling due to extra layer such as below

// wish to return both `FirstComponent` & `SecondComponent`, but you can't without Fragment

const renderComponent = () => {
  //return <FirstComponent /><SecondComponent /> // <<== this is invalid
  return <><FirstComponent/><SecondComponent /></> // similar result as above 
}

<View style={{flexDirection: 'row', justifyContent: 'space-between' }}>
  {renderComponent()}
</View>
like image 53
Isaac Avatar answered Sep 21 '25 11:09

Isaac


There is a difference in and <></> statements.

Everything in one view element is considered and one element for parent tag. But if you use Fragment(<></>). All the tags under fragment will be consider as separate element.

like image 37
Malik Abdullah Avatar answered Sep 21 '25 12:09

Malik Abdullah