0

I am new at react native and js.

I want to show my navbar when user starts to scrolling up at any time/position and hide my navbar when user starts to scrolling down at any position.

My first approach was using "animation" and "finding out scrolling direction" together but I failed. Can anyone show me detailed how it possible?

Thanks!

2 Answers2

1

Based on the similar requirement I had to hide an action bar located at the bottom of the screen when the user scrolls up(Hide) and ScrollDown(Show). Inspired by other answers. Here is what I did -

const [oldOffset, setOldOffset] = useState(0);

<ScrollView
  styleContainer={styles.container}
  onScrollBeginDrag={event => {
    const currentOffset = event.nativeEvent.contentOffset.y;
    setOldOffset(currentOffset);
    if (!(currentOffset < 0) && currentOffset !== 0) {
      if (currentOffset < oldOffset) {
        console.log('up');
      } else {
        console.log('down');
      }
    }
  }}
>
</ScrollView>

Since I wasn't too worried about delay in show/hide I made sure I don't get erroneous state.

ehtulhaq
  • 59
  • 7
0

In your scrollview, add the onScroll Function to your scrollview.

When the function get called, check for the direction of the scrolling:

var currentOffset = event.nativeEvent.contentOffset.y;
var direction = currentOffset > this.offset ? 'down' : 'up';
if(direction == 'down') {
    // hide the nav
} else {
    // show the nav
}

I hope it's help you!

  • I get error "cant find variable event". Can you give a little bit more detailed code please? Can you write for me exactly _onScroll() func please? :/ – Emre Şahiner Aug 07 '17 at 03:46
  • @EmreŞahiner you can have a look at this: https://stackoverflow.com/questions/29503252/react-native-get-current-scroll-position-of-scrollview/32070911 in the handle scroll, simpli copy / paste the code I posted below! Actually I can't write you the full function. Maybe tomorrow! – Charles-olivier Demers Aug 07 '17 at 03:49
  • thank you for your answer! I implement your suggestion and it works but when I scrolls both direction, always printed "up" (inside of else). **note that (this.offset returned "undefined" ) – Emre Şahiner Aug 07 '17 at 04:03
  • you need to set this.offset to currentOffset value at the end of your onScroll function – alpha Aug 07 '17 at 07:04
  • I have the same problem.In android the navbar show or hide will affect the contentoffset in onscroll func,and you cannot get the realtime frame in onscroll func.So this is not a good solution. – Devin Gong Aug 19 '19 at 07:03