0

I'm new to react native. I've used functional component instead of class that works fine. Here I can't use constructors, states , lifecycle methods etc. So I want to create a class instead of function but no luck.

Functional component (index.android.js)

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  Button,
  View
} from 'react-native';

import {
  TabNavigator
} from 'react-navigation';

import MyHomeScreen from './MyHomeScreen';
import MyNotificationsScreen from './MyNotificationsScreen';

const TabNavigation = TabNavigator({
  Home: {
    screen: MyHomeScreen,
  },
  Notifications: {
    screen: MyNotificationsScreen,
  },
}, {
  tabBarOptions: {
    activeTintColor: '#e91e63',
  },
});

AppRegistry.registerComponent('TabNavigation', () => TabNavigation);

MyHomeScreen.js

export default class MyHomeScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Home',
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={require('./chats-icon.png')}
      />
    ),
  };

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.navigate('Notifications')}
        title="Go to notifications"
      />
    );
  }
}

MyNotificationsScreen.js

export default class MyNotificationsScreen extends React.Component {
  static navigationOptions = {
    tabBarLabel: 'Notifications',
    tabBarIcon: ({ tintColor }) => (
      <Image
        source={require('./notif-icon.png')}
      />
    ),
  };

  render() {
    return (
      <Button
        onPress={() => this.props.navigation.goBack()}
        title="Go back home"
      />
    );
  }
}

Using class: I want to use class as follows. How can I make it work as in functional component named TabNavigation as above?

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  Button,
  View
} from 'react-native';

import {
  TabNavigator
} from 'react-navigation';

import MyHomeScreen from './MyHomeScreen';
import MyNotificationsScreen from './MyNotificationsScreen';    

export default class TabNavigation extends Component {

  render() {
    return (
      <View>
      //what to do here
      </View>
    );
  }
}   
Amrita Stha
  • 2,973
  • 3
  • 25
  • 46

1 Answers1

0

If you want to render TabNavigation at the top level then the way to do it is as in your first example. TabNavigator() constructs a component.

Your use case doesn't seem clear from your question, but if you want a class at the top level, you can wrap TabNavigation in a class:

// ...
render() {
  return (
    <TabNavigation />
  );
}
Freewalker
  • 6,329
  • 4
  • 51
  • 70