How do you create dynamic/update-able routes with react-native-tab-view?

1.7k views Asked by At

I have the following component. It works great to create the initial set of tabs.

import * as React from 'react';
import { TabBar, TabView } from 'react-native-tab-view';
import { CollectionList } from './components';

const renderTabBar = (props) => <TabBar {...props} scrollEnabled />;

const RarityTabs = ({ collectionId, rarities }) => {
  const rarityRoutes = rarities.map((rarity) => ({
    key: rarity.variant,
    title: rarity.quality,
    rarity,
  }));

  const [index, setIndex] = React.useState(0);
  const [routes, setRoutes] = React.useState(rarityRoutes);

  return (
    <TabView
      lazy
      navigationState={{ index, routes }}
      renderScene={({ route }) => (
        <CollectionList collectionId={collectionId} selectedRarity={route.rarity} />
      )}
      renderTabBar={renderTabBar}
      onIndexChange={setIndex}
    />
  );
};

export default RarityTabs;

However, rarities can change and I'd like to make the tab route creation respond accordingly.
When I try useEffect to to fire setRoutes it locks up the app.

How can do you create a way for routes to be dynamic? Thanks!

Also posted on GitHub

1

There are 1 answers

1
Muhammad Danish On
import * as React from 'react';
import {View, StyleSheet} from 'react-native';
import {TabView, TabBar, SceneMap} from 'react-native-tab-view';
import {connect} from 'react-redux';
import Categories from './Categories';

export default class CategoriesScrollable extends React.Component {
  constructor(props) {
    super(props);

    const {monthList, selected} = props;

    this.state = {
      index: selected,
      screens: {},
      routes: monthList,
    };
  }

  componentDidMount() {
    let screens = {};

    for (let i = 0; i < this.state.routes.length; i++) {
      screens[[`${this.state.routes[i].key}`]] = Categories;
    }
    this.setScreen(screens);
  }

  setScreen = (param) => {
    this.setState({screens: SceneMap(param)});
  };

  handleIndexChange = (index) =>
      this.setState({
        index,
      });

  renderTabBar = (props) => (
      <TabBar {...props} scrollEnabled />
  );

  render() {
    return (
        <View style={{flex: 1, backgroundColor: Color.white}}>
          {this.state.screens.length > 0 && (
              <TabView
                  ref={this.props.innerRef}
                  lazy={true}
                  swipeEnabled={false}
                  navigationState={this.state}
                  renderScene={this.state.screens}
                  renderTabBar={this.renderTabBar}
                  onIndexChange={this.handleIndexChange}
              />
          )}
        </View>
    );
  }
}