Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Native style a sticky header when it sticks

I've a short question: How can I apply a different style to a sticky header in a scrollview when it sticks?
I wanna add some shadow/elevation when it sticks.

Thank you :)

Environment

  • react-native: 0.45.0
like image 904
Daniel Lang Avatar asked Oct 30 '22 05:10

Daniel Lang


1 Answers

Currently React Native ScrollView component has a property called stickyHeaderIndices, even in your 0.45 version. You can use it to pass your header child index that should be sticky. After that you can use onScroll event to get current scroll position and when achieve your header size add a custom style with shadow. See for the example here:

https://snack.expo.io/@fabiodamasceno/scroll-sticky-styled

or if you prefer:

import * as React from 'react';
import { Text, View, ScrollView } from 'react-native';

const HEADER_HEIGHT = 20;
const headerStyle = {
  backgroundColor: '#e5e5e5',
  height: HEADER_HEIGHT
}
const myShadowStyle = {
  elevation: 3,
  shadowOpacity: 0.2,
  shadowRadius: 6,
  shadowOffset: {
    height: 3,
    width: 0,
  },
};

export default class App extends React.Component {
  state = {
     headerStyle : {
     ...headerStyle
    }
  }
  render() {
    return (
     <View style={{marginTop: HEADER_HEIGHT, height: 150}}>
      <ScrollView 
        stickyHeaderIndices={[0]} 
          onScroll={event => {
            const y = event.nativeEvent.contentOffset.y;
            if(y >= HEADER_HEIGHT)
              this.setState({
                headerStyle:{
                    ...headerStyle,
                    ...myShadowStyle
                }
              })
            else
              this.setState({
                  headerStyle:{
                      ...headerStyle,
                  }
                })
          }}
      >
        <View style={this.state.headerStyle}>
          <Text>My Header Title</Text>
        </View>
        <Text>Item 1</Text>
        <Text>Item 2</Text>
        <Text>Item 3</Text>
        <Text>Item 4</Text>
        <Text>Item 5</Text>
        <Text>Item 6</Text>
        <Text>Item 7</Text>  
        <Text>Item 8</Text>
        <Text>Item 9</Text>
        <Text>Item 10</Text>
        <Text>Item 11</Text>
        <Text>Item 12</Text>
        <Text>Item 13</Text>
        <Text>Item 14</Text>
      </ScrollView>
    </View>
    );
  }
}
like image 130
Fábio Damasceno Avatar answered Nov 18 '22 06:11

Fábio Damasceno