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

Time:09-30

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?

CodePudding user response:

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>

CodePudding user response:

<></> is a shortcut for <React.Fragment></React.Fragment> It is different from as it does not create a DOM element.

You can find more about Fragments here https://fr.reactjs.org/docs/fragments.html

CodePudding user response:

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.

  • Related