How to make FlatList fill the height? - react-native

import React from 'react';
import {SafeAreaView, KeyboardAvoidingView, FlatList, View, Text, TextInput, Button, StyleSheet } from 'react-native';
export default class Guest extends React.Component {
state={
command: '',
}
constructor(props) {
super(props)
this.onChangeText = this.onChangeText.bind(this)
this.onKeyPress = this.onKeyPress.bind(this)
this.onSubmit = this.onSubmit.bind(this)
}
onChangeText(text){
const command = text.replace('\n', '');
this.setState({
command: command
})
}
onKeyPress(e){
}
onSubmit(){
}
render() {
return(
<SafeAreaView style={styles.safeAreaView}>
<KeyboardAvoidingView style={styles.keyboardAvoidingView} keyboardVerticalOffset={88} behavior="padding" enabled>
<FlatList
inverted={true}
keyboardShouldPersistTaps='always'
keyboardDismissMode='interactive'
ref='list'
style={styles.flatList}
data={[1, 2, 3]}
renderItem={(props) => {
return(<View><Text>{props.item}</Text></View>)
}}
/>
<TextInput
command={this.state.command}
onChangeText={this.onChangeText}
onKeyPress={this.onKeyPress}
onSubmit={this.onSubmit}
style={styles.textInput}
/>
</KeyboardAvoidingView>
</SafeAreaView>
)
}
}
const styles = StyleSheet.create({
safeAreaView:{
backgroundColor:"#ffffff",
},
keyboardAvoidingView:{
},
flatList:{
backgroundColor: 'red',
},
textInput:{
backgroundColor: 'yellow'
}
})
I'd like the red flatList to fill the screen (but keep height of yellow textbox).
I've tried flex:1 on flatList, but it simply makes it disappear.

FlatList inherits ScrollView's props, so solution for ScrollView will work:
<FlatList
contentContainerStyle={{ flexGrow: 1 }}
{...otherProps}
/>
Here is the original Github issue for above solution.
EDIT: The parental Views of FlatList should have flex: 1 in their style.
safeAreaView:{
backgroundColor:"#ffffff",
flex: 1
},
keyboardAvoidingView:{
flex: 1
},

use the property style wit flex:
render() {
return (
<View style={{ flex: 1 }}>
<FlatList
keyExtractor = { this.keyExtractor }
data = { this.getPOs() }
ListEmptyComponent = { this.renderEmpty }
ItemSeparatorComponent = { Separator }
renderItem = { this.renderItem }
/>
</View>
)
}

No need to add a parental view to the list, simply:
render() {
return <FlatList style={{width: '100%', height: '100%'}}
{...others}
/>;
}

you can also add height in flatList style or put flatlist inside a view and then add flex for view

In my case the problem was with virtual keyboard. when I open another page. then the keyboard suddenly dismiss. and it cause part of the page to be like someone cut it or clean it. so the solution is to before push the page that contain flatlist first dismiss the keyboard and then navigate to new page

I try every response on this issue but none of them work.
What I do was add a Parent to the FlatList and then give it a style :
<View style={{ height: SCREEN_HEIGHT}}>
SCREEN_HEIGHT is from Dimensions.get('window')
you have to import from "react-native" like this:
import { Dimensions } from "react-native"
Full example:
<View style={{ height: SCREEN_HEIGHT}}>
<FlatList
contentContainerStyle={{ flexGrow: 1 }}
keyExtractor={item => item.name}
numColumns={1}
data={this.state.dataList}
renderItem={({ item, index }) =>
this._renderItemListValues(item, index)
}
/>
</View>

Related

How to change only the active button background color [React-Native]

import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
class App extends Component {
constructor(props){
super(props)
this.state={
selected:null
}
}
handle=()=>{
this.setState({selected:1})
}
render() {
return (
<View>
<TouchableOpacity style={[styles.Btn, {backgroundColor:this.state.selected===1?"green":"white"}]} onPress={this.handle}>
<Text style={styles.BtnText}>Button 1</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.Btn} onPress={this.handle}>
<Text style={styles.BtnText}>Button 2</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.Btn} onPress={this.handle}>
<Text style={styles.BtnText}>Button 3</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
Btn: {
borderWidth: 1,
width: 100,
height: 20,
borderRadius: 8,
margin: 5,
padding: 10,
justifyContent: 'center',
flexDirection: 'row',
alignItems: 'center',
},
BtnText: {
fontSize: 15,
},
});
export default App;
Snack Link : https://snack.expo.dev/U_fX-6Tao-
I want to make it so when I click a button, the active button backgroundColor should change to "green" and text to "white" and the rest of the buttons backgroundColor and textColor should stay "red". But when I click another button then that button should become active and the previous active button should get back to its normal state.
It would be wonderful if you could also explain the logic behind it as I'm a newbie in React Native.
Thank you.
You are always setting the active button to the first one. Also, I would use an array to render the buttons. I would do something like this:
class App extends Component {
constructor(props){
super(props)
this.state = {
selected: null
}
}
handlePress = (item) => {
this.setState({ selected: item })
}
render() {
return (
<View>
{[...Array(3).keys()].map((item) => {
return (
<TouchableOpacity key={item} style={[styles.Btn, {backgroundColor: this.state.selected === item ? "green" : "white" }]} onPress={() => this.handlePress(item)}>
<Text style={styles.BtnText}>Button {item + 1}</Text>
</TouchableOpacity>
)
})}
</View>
);
}
}
I created an Themed component(OK I did not create it. It is there when I create the app with Expo).
import { useState } from 'react';
import { TouchableOpacity as DefaultTouchableOpacity } from 'react-native';
export type TouchableProps = DefaultTouchableOpacity['props'] & { activeBgColor?: string };
export function TouchableOpacity(props: TouchableProps) {
const [active, setActive] = useState(false);
const { style, activeBgColor, ...otherProps } = props;
if (activeBgColor) {
return (
<DefaultTouchableOpacity
style={[style, active ? { backgroundColor: activeBgColor } : {}]}
activeOpacity={0.8}
onPressIn={() => setActive(true)}
onPressOut={() => setActive(false)}
{...otherProps}
/>
);
}
return <DefaultTouchableOpacity style={style} activeOpacity={0.8} {...otherProps} />;
}
Then I use this TouchableOpacity everywhere.
<TouchableOpacity
style={tw`rounded-sm h-10 px-2 justify-center items-center w-1/5 bg-sky-400`}
activeBgColor={tw.color('bg-sky-600')}
>
<Text style={tw`text-white font-bold`}>a Button</Text>
</TouchableOpacity>
Oh I am writing TailwindCSS with twrnc by the way. You will love it.
See the screenshot below.

React Native Keyboard Avoiding View

I'm trying to implement a flatlist of comments alongside a textinput at the bottom. However, when I try to place the textinput in a keyboard avoiding view so that it gets pushed to the top to see the input being typed in, it doesn't go to the top and stays at the bottom. Here is my code:
render() {
return (
<KeyboardAvoidingView enabled behavior='padding' style={styles.container}>
<View style={styles.commentStyles}>
<FlatList
keyExtractor={(item) => JSON.stringify(item.date)}
data={this.props.post.comments}
renderItem={({item}) => (
<View style={[styles.row, styles.commentContainer]}>
<Image style={styles.roundImage} source={{uri: item.commenterPhoto}}/>
<View style={[styles.left]}>
<Text>{item.commenterName}</Text>
<Text style={styles.commentText}>{item.comment}</Text>
</View>
</View>
)}
/>
<TextInput
style={styles.input}
onChangeText={(comment) => this.setState({comment})}
value={this.state.comment}
returnKeyType='send'
placeholder='Add Comment'
onSubmitEditing={this.postComment}
/>
</View>
</KeyboardAvoidingView>
);
}
My container just has a flex: 1 styling applied to it. I tried reading through the documentation for KeyboardAvoidingView but found it to be very confusing. If you guys can help me in any way, would greatly appreciate it!
Give this a try.
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
KeyboardAvoidingView,
Platform,
Dimensions,
TextInput
} from 'react-native';
const {height: fullHeight} = Dimensions.get('window');
class Comment extends Component {
constructor(props) {
super(props);
this.state = {
pageOffset: 0,
};
}
onLayout = ({
nativeEvent: {
layout: {height},
},
}) => {
const pageOffset =
fullHeight - height;
this.setState({pageOffset});
};
render() {
return (
<View style={styles.viewContainer} onLayout={this.onLayout}>
<KeyboardAvoidingView
style={styles.container}
keyboardVerticalOffset={this.state.pageOffset}
behavior={Platform.OS === 'ios' ? 'padding' : null}>
<FlatList
keyExtractor={(item) => JSON.stringify(item.date)}
data={this.props.post.comments}
renderItem={({item}) => (
<View style={[styles.row, styles.commentContainer]}>
<Image style={styles.roundImage} source={{uri: item.commenterPhoto}}/>
<View style={[styles.left]}>
<Text>{item.commenterName}</Text>
<Text style={styles.commentText}>{item.comment}</Text>
</View>
</View>
)}
/>
<TextInput
style={styles.input}
onChangeText={(comment) => this.setState({comment})}
value={this.state.comment}
returnKeyType='send'
placeholder='Add Comment'
onSubmitEditing={this.postComment}
/>
</KeyboardAvoidingView>
</View>
);
}
}
export default Comment;
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'space-between',
},
viewContainer: {
flex: 1,
},
});

Make autoscroll viewpager in reactnative

I am trying to make the sliding image. I have followed the this . Its responding on sliding with fingers but not sliding automatically. How can I do so? I have implemented as follows:
<ViewPager style={styles.viewPager} initialPage={0}>
<View key="1">
<Image style={ {height: '100%', width:'100%'}}source={{uri :'https://images.unsplash.com/photo-1441742917377-57f78ee0e582?h=1024'}}></Image>
</View>
<View key="2">
<Image style={ {height: '100%', width:'100%'}}source={{uri :'https://images.unsplash.com/photo-1441716844725-09cedc13a4e7?h=1024'}}></Image>
</View>
</ViewPager>
By looking at the source code I have found there is a method setPage() which accepts page number as argument.
Look at the example code they have provided where you can find how to use reference and call setPage method Example
Now you can use setInterval() and make auto slide work.
setInterval(() => {
this.viewPager.current.setPage(page);
}, 1000);
Set page is a method to update the page of the viewpager. You can autoscroll the viewpager using a timer and by updating the pager by using the setPage method. Below is the complete code for the same.
import React, { Component } from 'react';
import { StyleSheet, View, Text, Platform } from 'react-native';
import ViewPager from '#react-native-community/viewpager';
export default class App extends Component {
state = {
pageNumber: 0,
totalPage: 2
}
componentDidMount() {
var pageNumber = 0;
setInterval(() => {
if (this.state.pageNumber >= 2) {
pageNumber = 0;
} else {
pageNumber = this.state.pageNumber;
pageNumber++;
}
console.log(pageNumber)
this.setState({ pageNumber: pageNumber })
this.viewPager.setPage(pageNumber)
}, 2000);
}
render() {
return (
<View style={{ flex: 1 }}>
<ViewPager style={styles.viewPager} initialPage={0}
ref={(viewPager) => { this.viewPager = viewPager }}
scrollEnabled={true}>
<View key="1">
<Text style={{ color: 'black' }}>First page</Text>
</View>
<View key="2">
<Text>Second page</Text>
</View>
<View key="3">
<Text>Third page</Text>
</View>
</ViewPager>
</View>
);
}
}
const styles = StyleSheet.create({
viewPager: {
flex: 1,
},
});

React Native - WebView & FlatList in a ScrollView to be scrollable

I'm making a view in react native but my component has a webview to display HTML, below the webview is a flatlist( list of items)
The parent component is supposed to be scrollable based on the webview & the flatlist.
I tried to put them together but it doesn't work as I want.
Therefore I would appreciate all of your advice & suggestions. Thank you
Updated:
I found out a solution here after the owner of the lib has been updated
https://github.com/iou90/react-native-autoheight-webview/issues/81
You can use WebView as a header component of FlatList as this:
<View style={styles.container}>
<FlatList
data={[
{ key: 'a' },
{ key: 'b' },
{ key: 'c' },
{ key: 'd' },
]}
renderItem={({ item }) => <Text>{item.key}</Text>}
ListHeaderComponent={
<View style={{ height: 200 }}>
<WebView
originWhitelist={['*']}
source={{ html: '<h1>Hello world</h1>' }}
/>
</View>
}
/>
</View>
But there is still a limitation, you have to specify the height of the view that wraps WebView as done above.
Hope, you got the idea ?
Maybe this will help.
import React, { Component } from 'react';
import { Text, View, StyleSheet, WebView, FlatList } from 'react-native';
export default class App extends Component {
onNavigationStateChange = navState => {
if (navState.url.indexOf('https://www.google.com') === 0) {
const regex = /#access_token=(.+)/;
let accessToken = navState.url.match(regex)[1];
console.log(accessToken);
}
};
render() {
const url = 'https://api.instagram.com/oauth/authorize/?client_id={CLIENT_ID}e&redirect_uri=https://www.google.com&response_type=token';
return (
<View style={{flex: 1}}>
<WebView
source={{
uri: url,
}}
scalesPageToFit
javaScriptEnabled
style={{ flex: 1 }}
/>
<FlatList data={[1, 2, 3]} renderItem={(item) => <Text>item</Text>}/>
</View>
);
}
}

How to populate a Flatlist from TextInput

I am trying to populate a FlatList row with the value coming from a TextInput.
Below you can find my current code.
import React, { Component } from 'react'
import { View, Text, TouchableOpacity, TextInput, StyleSheet,
StatusBar, FlatList } from 'react-native'
globalText = require('../styles/Texts.js');
globalColors = require('../styles/Colors.js');
class SearchInput extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
ingredients: ''
}
}
_handleIngredients = (text) => {
this.setState({ ingredients: text })
}
render(){
return (
<View style={styles.container}>
<StatusBar barStyle="dark-content"/>
<View>
<TextInput style={[globalText.btnFlatPrimary, styles.inputText]}
underlineColorAndroid='transparent'
placeholder='Add ingredients'
placeholderTextColor={globalColors.lightGrey}
autoCapitalize='sentences'
autoCorrect={false}
autoFocus={true}
onChangeText={this._handleIngredients}
keyboardShouldPersistTaps='handled'
/>
</View>
<FlatList
data={this.state.data}
renderItem={({text}) => (
<View style={styles.cell}>
<Text style={globalText.btnFlatPrimary}>{this.state.ingredients}</Text>
</View>
)}
/>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
paddingTop: 20,
backgroundColor: globalColors.white,
},
inputText: {
paddingLeft: 16,
paddingRight: 16,
height: 60
},
cell: {
height: 60,
paddingLeft: 16,
justifyContent: 'center',
}
});
export default SearchInput;
I am probably missing something but if I pre populate the data and the ingredients states, then FlatList display correctly with the entered values. What I'd like it to populate the Flalist with the TextInput
data: [{key:'a'}],
ingredients: 'tomato'
Flatlist will only re-render if the data property changes. If you want it to re-render based on other values, you would need to pass an extraData prop.
<FlatList
data={this.state.data}
extraData={this.state.ingredients} //here
renderItem={({text}) => (
<View style={styles.cell}>
<Text style={globalText.btnFlatPrimary}>{this.state.ingredients}</Text>
</View>
)}
/>
Read more here: https://facebook.github.io/react-native/docs/flatlist.html#extradata
change: onChangeText={this._handleIngredients}
to: onChangeText={(text) => this._handleIngredients(text)}
This is for preserving the scope of this.