Akshay Dusane
Akshay Dusane

Reputation: 310

How do I dynamically change functional components in a Parent component in React Native?

I am new React and React Native. Let's say I have

   <View>
     <View>
       "Here there will be my functional components that will change dynamically based on routes"
     </View>
   </View>

How do I achieve this. I explored React Navigation but did not get it. What will be ideal way to do this ? Also I want to achieve this using Stack Navigator.

Upvotes: 0

Views: 199

Answers (1)

Guruparan Giritharan
Guruparan Giritharan

Reputation: 16334

You can take two approaches for this. 1. Use the name of the route you provide and get the route.name and decided the content 2. Pass an initial param and decide the content based on that.

The below code shows both approaches you can chose whatever is easy for you. Still having separate components would be the ideal way if you are going to put a lot of logic inside.

function HomeScreen({route}) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
     {route.params.id==="Test1" && <Text>{route.params.id}</Text>}
      {route.name==="Home2" && <Text>"Home 2"</Text>}
      <Text>Home Screen</Text>
    </View>
  );
}

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="Home" component={HomeScreen} initialParams={{id:"Test1"}}/>
        <Stack.Screen name="Home2" component={HomeScreen} initialParams={{id:"Test2"}}/>
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Upvotes: 1

Related Questions