skip to Main Content

I am trying to centre my search component (horizontally and vertically) using flex. It works fine on the web view, but on the Native view it does not centre vertically. I am using expo which has several available methods to view the app:

Screenshot of expo app output

Here is the App.tsx

import React from 'react';
import { View } from 'react-native';
import Search from './components/Search';

const styles: any = {
  container:{
    flex: 1,
    margin: 20,
    alignItems: 'center',
    justifyContent: 'center'
  }
}
const App = () => {

  return (
    <View style={styles.container} >
      <Search/>
    </View>
  );
};

export default App;

and here is Search.tsx

import React, { useState, useEffect } from 'react';
import { View, TextInput, FlatList, Text } from 'react-native';

const Search = () => {
  const [searchTerm, setSearchTerm] = useState('');
  const [results, setResults] = useState([]);

  useEffect(() => {
    let timerId: any = null;
    if (searchTerm.length >= 2) {
      clearTimeout(timerId);
      timerId = setTimeout(() => {
        fetch(`http://localhost:8080/search/${searchTerm}`)
          .then((response) => response.json())
          .then((data) => setResults(data.results))
          .catch((error) => console.error(error));
      }, 500);
    } else {
      setResults([]);
    }

    return () => clearTimeout(timerId);
  }, [searchTerm]);

  return (
    <View>
      <TextInput
        value={searchTerm}
        onChangeText={(text) => setSearchTerm(text)}
        placeholder="Search"
      />
      <FlatList
        data={results}
        keyExtractor={(item) => item}
        renderItem={({ item }) => (
          <Text>{item}</Text>
        )}
      />
    </View>
  );
};


export default Search;

2

Answers


  1. Chosen as BEST ANSWER

    I achieved it by setting the width of parent View in Search.tsx to 100% and then adding an additional View component inside the container View inside App.tsx.

    Search.tsx changes

        <View style={{ width: '100%' }}>
        <TextInput
          value={searchTerm}
          onChangeText={(text) => setSearchTerm(text)}
          placeholder="Search"
        />
        <FlatList
          data={results}
          keyExtractor={(item) => item}
          renderItem={({ item }) => (
            <Text>{item}</Text>
          )}
        />
      </View>
    

    app.tsx changes

      <View style={styles.container}>
        <View >
          <Search />
        </View>
      </View>
    

    Shout out to ChatGPT for the solution (after some attempts)


  2. The wrapping View inside Search will span the whole screen and the list inside it will only take as much space as it needs. Apply flex: 1 to your flatlist or justifyItems: “center” to the wrapping view.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search