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:
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
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
app.tsx changes
Shout out to ChatGPT for the solution (after some attempts)
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.