Search code examples
androidandroid-viewpagerreact-native

How to pass array of View/Component in react native?


I am making App framework in React Native. Framework consist of some basic screens like login screen, Tab screen. The purpose of the framework is to provide fundamental design to new app which will be developed from grounds up.

Tab Screen

As we know each Tab will have individual view to display. I want to make tabscreen totally customizable. It means based on passed View list and tab list, it should render.

For that i need to pass Array of View/Component as a prop to TabScreen.

  1. How can I make array of View/Component?
  2. How to pass array as props to TabScreen?

below is the code of TabScreen

'uses strict'

import {StyleSheet, View, Text, Image} from 'react-native';
import React, {Component, PropTypes} from 'react';
import {IndicatorViewPager, PagerTabIndicator} from 'rn-viewpager';

export default class TabScreen extends Component {
  
  constructor (props) {
    super(props)
  }
  
  static propTypes = {
    views : PropTypes.arrayOf(PropTypes.instanceOf(View)).isRequired,
    tabs: PropTypes.arrayOf(PropTypes.shape({
      text: PropTypes.string,
      iconSource: Image.propTypes.source,
      selectedIconSource: Image.propTypes.source
    })).isRequired,
  }
  render() {
    
    return (
      <View style={{flex:1}}>
      <IndicatorViewPager
      style={{flex:1, paddingTop:20, backgroundColor:'white'}}
      indicator={<PagerTabIndicator tabs={this.props.tabs} />}>
      {views}
      </IndicatorViewPager>
      </View>
    );
  }
}
module.exports = TabScreen;

Please help


Solution

  • You don't need to pass an array of react native components, you have to use the children of the component, like this:

    In the render method of your upper-level component:

    <TabScreen>
        <View><Text>First tab</Text>
        <View><Text>Second tab</Text></View>
        {/* And so on... */}
    </TabScreen>
    

    Then, in your TabScreen component, just do:

    render() {
    
        return (
          <View style={{flex:1}}>
          <IndicatorViewPager
          style={{flex:1, paddingTop:20, backgroundColor:'white'}}
          indicator={<PagerTabIndicator tabs={this.props.tabs} />}>
          {this.props.children}
          </IndicatorViewPager>
          </View>
        );
      }
    

    In any case, in response to your questions:

    How can I make array of View/Component?

    Just as any other array. For instance, with a map:

    let elements = ['First Tab', 'Second Tab'].map((text)=> <View><Text>{text}</Text></View>))
    

    How to pass array as props to TabScreen?

    Arrays are no different to any other data type when it comes to props (any variable can be passed as a prop, unless it has some sort of validation mechanism, in which case it will raise a warning).