Search code examples
react-nativenative-basesegment

Changing segment content onPress


I have segments and I want them to act as tabs. I tried using react-navigation onPress of each segment but it doesn't look nice.

I want the segments to stay fixed at the top and on clicking each one the content should change or call a specific component without reloading or noticing that the screen has changed.

<Segment>
  <Button first>
    <Text>Puppies</Text>
   </Button>
   <Button>
    <Text>Kittens</Text>
    </Button>
    <Button last active>
      <Text>Cubs</Text>
    </Button>
</Segment>
<Content>
  <Text>Awesome segment</Text>
</Content>

Solution

  • Segments can be customized as a react-navigation single screen separated into multiple components which can be rendered on demand.

    Example

    (Using native-base components)

    state = {
        activePage:1,
    }
    
    selectComponent = (activePage) => () => this.setState({activePage})
    
    _renderComponent = () => {
      if(this.state.activePage === 1)
        return <Component1/> //... Your Component 1 to display
      else 
        return <Component2/> //... Your Component 2 to display
    }
    
    render() {
      return ( 
        <Container>
          <Header>
           <Left />
           <Body>
             <Segment>
               <Button active={this.state.activePage === 1}
                  onPress={this.selectComponent(1)}><Text>Component 1</Text></Button>
               <Button  active={this.state.activePage === 2}
                  onPress= {this.selectComponent(2)}><Text>Component 2</Text></Button>
             </Segment>
            </Body>
            <Right/>
           </Header>
           <Content padder>
            {this._renderComponent()}
           </Content>
          </Container>
      )
    }
    

    You can customize it to add more components based on the conditions set above

    Edit

    Supposing you navigate to a particular screen that also contains Segment, the on some item button click you can do

    this.props.navigation.navigate('OtherSegmentScreen', {activePage: this.state.activePage})
    

    And on that page receive the props as

    const {navigate} = this.props.navigation
    const previousActiveSegment = navigate.getParams('activePage', '1') //... 1 is default value that you can set