An approach to concealing a search bar while scrolling down and revealing it while scrolling up in react-native

Looking for help with implementing a disappearing search bar functionality when scrolling? Check out the following code snippets and examples that demonstrate how to achieve this feature:

showSearchBarIOS = () => {
    return (
      <View style={styles.containerSearchBarIOS}>
        <Icon name="search" size={20} style={{ marginLeft: 5 }} />
        <TextInput
          style={styles.textInputIos}
          value={this.state.text}
          autoCorrect={false}
          returnKeyType="done"
          onChangeText={this.submitText}
          placeholder="Buscar..."
          placeholderTextColor={GRIS_DEFAULT}
        />
        <Text>{this.props.texto}</Text>
      </View>
    );
  };

  showSearchBarAndroid = () => {
    return (
      <View style={styles.containerSearchBarAndroid}>
        <Icon
          name="search"
          size={25}
          style={{ marginLeft: 5, marginBottom: 3 }}
        />
        <TextInput
          style={styles.textInputAndroid}
          value={this.state.text}
          autoCorrect={false}
          returnKeyType="done"
          onChangeText={text => this.setState({ text: text })}
          placeholder="Buscar Diputados..."
          placeholderTextColor={GRIS_DEFAULT}
        />
      </View>
    );
  };

showList = () => {
    return (
      <View style={{ flex: 1 }}>
        {Platform.OS === "ios"
          ? this.showSearchBarIOS()
          : this.showSearchBarAndroid()}
        <RecyclerListView
          layoutProvider={this._layoutProvider}
          dataProvider={this.props.dataProvider}
          rowRenderer={this._rowRenderer}
          scrollViewProps={{
            refreshControl: (
              <RefreshControl
                refreshing={this.props.diputadosNomina.isFetching}
                onRefresh={this.props.fetchDiputadosNomina}
                colors={[REFRESH_CONTROL_COLOR]}
                tintColor={REFRESH_CONTROL_COLOR}
              />
            )
          }}
        />
      </View>
    );
  };

container: {
    flex: 1,
    backgroundColor: PAGE_BACKGROUND_COLOR
  },
  containerSearchBarIOS: {
    flexDirection: "row",
    alignItems: "center",
    height: 30,
    padding: 0,
    marginLeft: 6,
    marginRight: 6,
    marginTop: 5,
    backgroundColor: BACKGROUND_SEARCH_BAR,
    borderWidth: 1,
    borderColor: GRIS_DEFAULT,
    borderRadius: 60
  },
  containerSearchBarAndroid: {
    flexDirection: "row",
    alignItems: "center",
    height: 40,
    padding: 0,
    marginLeft: 2,
    marginRight: 2,
    marginBottom: 5,
    marginTop: 5,
    backgroundColor: BACKGROUND_SEARCH_BAR,
    borderWidth: 1,
    borderColor: GRIS_DEFAULT,
    borderRadius: 60
  },
  textInputIos: {
    fontSize: 14,
    fontFamily: Roboto_Regular,
    width: "90%",
    padding: 2
  },

textInputAndroid: { fontSize: 13, fontFamily: Roboto_Regular, width: "90%" }

Answer №1

Take a look at this sandbox. Essentially, it consists of the following code snippet:

    const HideOnScroll = () => {
    const [scroll, setScroll] = React.useState(window.scrollY);
    const [visible, setVisible] = React.useState(false)
    React.useEffect(() => {
        const onScroll = () => {
            setVisible(window.scrollY > scroll)
            setScroll(window.scrollY)
        }
        window.addEventListener("scroll", onScroll);
        return () => window.removeEventListener("scroll", onScroll);
    });

    return (
        <div style={{ height: "200vh" }}>
            {visible && (
                <div style={{ position: "fixed" }}>Only show while scrolling down</div>
            )}
        </div>
    );
}

Answer №2

If you're looking to learn how to implement a search bar hide/show effect on scroll up/down, check out this informative medium blog:

Answer №3

Maybe something along these lines?

componentDidMount(){
    this.previousScrollPosition = window.scrollY;
    this.isVisible = false;
    window.addEventListener('scroll', e => this.handleNavigation(e));
}

handleNavigation = (e) =>{
    const currentWindow = e.currentTarget;

    if(this.previousScrollPosition > currentWindow.scrollY){
        this.isVisible = true;
    }
    else if(this.previousScrollPosition < currentWindow.scrollY){
        this.isVisible = false;
    }
    this.previousScrollPosition = currentWindow.scrollY;
};

render () {
  return (
    <Fragment>
      { this.isVisible && <SearchBar /> }
    </Fragment>
  )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Form featuring two buttons with distinct values for submitting

<form action="here.php" method="POST"> <input type="text" name="text"> <div id="one"> <input type="hidden" name="aaa" value="one"> <input type="submit" value="Send"> </div> <div id="two"> <input type= ...

Learn the process of incorporating a plugin into a React JS project

As a ReactJs beginner, I am encountering an issue while trying to import a new plugin in my react app. I am currently working on React without using node or npm as shown below. <!-- some HTML --> <script src="https://unpkg.com/babel-standalone@6 ...

What is the best way to implement a hover feature on a Vue / Vuetify Autocomplete dropdown list?

I'm not very experienced with Vue and I'm finding it a bit complex to grasp. Perhaps you guys can provide the "best practice" or most efficient solution for my issue: I have an autocomplete dropdown box. When expanded, it shows a list with click ...

Creating JavaScript accessors for Java beans

Is there a Java framework available that can automatically generate JavaScript code to access backend beans? For instance, suppose I have a Spring service named TestService: public interface TestService { public static class UserDTO { public S ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

Clicking on a jQuery element will reveal a list of corresponding elements

I've retrieved a list of elements from the database and displayed them in a table with a button: <a href="#" class="hiden"></a> To show and hide advanced information contained within: <div class="object></div> Here is my jQ ...

The Vue-router is constantly adding a # symbol to the current routes, and it's important to note that this is not the typical problem of hash and

After setting up my router file using Vue 3, it looks like this: import { createRouter, createWebHistory } from "vue-router"; import Home from "../views/Home.vue"; const routes = [ { path: "/", name: &quo ...

Linking Elements in Angular Framework

I'm currently working on a website using Angular that is set up as a Multi-Page Application (MPA). Each page is a separate component that I have developed, but I'm unsure how to connect them together. I want users to be directed to different page ...

Using Firebase data within a Bootstrap modal interface

Recently, I've been working on a website project where I'm utilizing the Firebase Realtime Database to retrieve user-inserted data and display it as Bootstrap Cards, just like in these images: Firebase Realtime Database - 1st card Firebase Real ...

Acquiring the assigned class attribute

I have an image that triggers ajax requests when clicked. To pass a variable from $_GET[] to my onclick function, I came up with the following solution: <img id="img1" class="<?=$_GET['value']"?> /> and using jQue ...

Switching user agents to access mobile websites

I'm currently using JavaScript to redirect the main website to the mobile website, but I'm struggling to switch back to desktop view on a mobile device. Is there any way to provide a link labeled "Full Website" that redirects to the main website ...

What steps can be taken to avoid including empty tasks in React code?

Is there a way to prevent my application from adding empty tasks? Below is the code snippet for adding a new task to an array. How can I implement a condition to block the addition of empty tasks? This application follows Mozilla's guidelines for a R ...

Can anyone figure out why this code is not functioning properly? It seems to be targeting the body element and all of

Currently, I am utilizing jqtouch to create a mobile website. In addition to this, I am incorporating a gallery image slider into the website. However, I have encountered an issue where the images do not display when placed between <div id="project_name ...

The Kendo grid row mysteriously vanished while trying to edit it immediately after inserting a new row

I have configured a Kendo grid in the following manner, but I am encountering an issue where after adding a row, it disappears when I attempt to edit it before sending the changes to the server. However, upon refreshing the page, the row reappears. Any i ...

Combine a JSON object and a JSON array by matching the value of the JSON object to the key of the JSON array

I am looking to create a JSON array in node by combining two JSON objects and arrays. `var template = { "key1": "value1", "key3": "value3", "key4": "value3", "key6": "Dummy Value1" }; var data = [ { "value1": "1", "value2": "2", ...

Creating a custom pipe that converts seconds to hours and minutes retrieved from an API can be achieved by implementing a transformation function

Can someone please provide guidance on creating a custom pipe in Angular 8 that converts seconds to hours and minutes? Thank you. <div class="col-2" *ngFor="let movie of moviesList"> <div class="movie"> {{ movie.attributes.title }} ...

Minimize the size of your compiled JavaScript with GWT

Recently, I've noticed that the size of my compiled JavaScript is increasing more quickly than I anticipated. Just a few additional lines of Java code in my project can result in a significant increase in script size by several Kbs. Currently, my com ...

Improving user input in AngularJS

My goal is to create a filter that converts time into seconds, such as: 01:30:10 becomes 5410, and vice versa. This way, the model only holds seconds while providing users with a more user-friendly representation. I've successfully implemented a work ...

Javascript function always runs last despite being called first

I am facing a situation where I have two functions associated with the Vue object named "form": form.sizeChartAsImage(); form.setSizeChart(); The code for these functions is as follows: setSizeChart: function () { for (i = 0; i < this.col ...

Show the user's input on the canvas

Currently, my setup consists of 3 elements - a text field and a submit button at the top, with a canvas below them. I am looking for a way to showcase user input on the canvas after they click the submit button. If you have any JavaScript suggestions, I w ...