A navigator can only contain 'Screen', 'Group' or 'React.Fragment' as its direct children

Viewed 5517
<Stack.Navigator>
  {
    isLogin ? <ComponentA /> :  <ComponentB />
  }
</Stack.Navigator>


const ComponentA = () => (
 arrA.map( v => <Stack.Screen name={v.name} component={v.component} />)
)

const ComponentB = () => (
 arrB.map( v => <Stack.Screen name={v.name} component={v.component} />)
)

i want use some hooks in componentA and componentB, so i have to use them as function component, any help please?

source code

4 Answers

An option could be to render the components inline:

<Stack.Navigator>
  {
    isLogin ? ComponentA({}) :  ComponentB({})
  }
</Stack.Navigator>

What exactly are you trying to do? Please elaborate.

Anyway, I think a general direction would be:

const componentA = props => {
// Whatever you wanna do

return (<>
{arrA.map( v => <Stack.Screen name={v.name} component={v.component} />)}
</>)

}

Same for componentB

I think this is could be a bug for react-navigation but i found a solution to fix the error.

Solution:

  1. Remove the Stack.Screen that caused the problem from Stack.Navigator
  2. Then copy and paste last Stack.Screen item in your Stack.Navigator
  3. Change the name and component props to your new screen but don't save the changes
  4. Restart metro server and emulator
  5. run your project and you will see error no more existed.

1. Make sure you have installed '@react-navigation/native' and '@react-navigation/stack'.

npm install @react-navigation/native
npm install @react-navigation/stack

2. Make sure to have react-navigation properly sat up:

On iOS:

cd ios
pod install

On Android: Locate this file: android/app/build.gradle and add the following under dependencies

implementation 'androidx.appcompat:appcompat:1.1.0-rc01'
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02'

3. Try to restart Metro and Emulator (in the terminal, just use Ctrl + C or Cmd + C). Then try to restart it again.

npx react-native start // running metro
npx react-native run-android // running the android emulator, replace `run-android` with `run-ios`, if you want to use the iOS simulator. 
Related