How to select FlatList item in React Native? - javascript

I have this code :
renderRooms = ({item:room}) => {
return(
<View style={styles.cards}>
<View style={styles.cardRight}>
<View style={{ marginLeft:2, alignItems: 'center', flex:1 }}>
<Text style={{fontSize:12, marginTop:10, marginBottom: 5, color:'#B0B0B0'}}>
Harga/malam
</Text>
<Text style={{fontSize:12, textDecorationLine:'line-through'}}>
{`${'Rp.'}${room.pricing.normal}`}
</Text>
<Text style={{fontSize:14, fontWeight:'800', color:'#26de81', }}>
{`${'Rp.'}${room.pricing.discount}`}
</Text>
<CheckBox
// center
iconRight
title={this.state.showContinueToPayment == true ? 'Batal' : 'Pilih'}
checked={this.state.showContinueToPayment}
containerStyle={{padding:5, borderColor:'white', backgroundColor:'white'}}
onPress={() => this.setState({showContinueToPayment: !this.state.showContinueToPayment})}
/>
</View>
</View>
</View>
)
}
on this part :
<CheckBox
iconRight
title={this.state.showContinueToPayment == true ? 'Batal' : 'Pilih'}
checked={this.state.showContinueToPayment}
containerStyle={{padding:5, borderColor:'white', backgroundColor:'white'}}
onPress={() => this.setState({showContinueToPayment: !this.state.showContinueToPayment})}
/>
I want to be able to set the state of my checkbox, but I can't make it done.
I'm using a FlatList, when I render my app, this renderRooms give me 2 list. I think the problem is these 2 list should have their own state. But I don't know how to do it.
Looking for some helps. Thanks beforehands.

Related

React Native flatlist takes a while to update items

So i am currently making a messaging application and this needs to be able to live messages, I am using a flat list to display these items and everytime i append an item to the messageFetch it takes ages for the flat list to load, (at any time there could be 100's to 1000's of items in the list). How can I speed this up? Also the components are of diffrent sizes.
flatlist component:
<View style={styles.container}>
<View style={styles.topBar} focusable>
<Text style={{ fontFamily: "Roboto-Regular", fontSize: 17, color: "white" }}>{name}</Text>
</View>
<View style={styles.mainChat} focusable>
<View style={[styles.loading, { display: loadedFinished ? "none" : "flex" }]}>
<ActivityIndicator style={[styles.loading, { display: loadedFinished ? "none" : "flex" }]} />
</View>
<FlatList
inverted
ref={list}
data={messageFetch.reverse()}
renderItem={Message}
keyExtractor={(item) => item.index}
/>
</View>
</View>
loadedFinished only runs once and stops at about 3 seconds.
Message Component:
function Message({ item }) {
if (item.embed.type != undefined) {
return <Text>hello<Text>
}
return (
<View style={[mesgStyles.mainMessage, { flexDirection: item.original ? "row-reverse" : "row" }]}>
<Image style={mesgStyles.userPfp} resizeMode="contain" source={{ uri: item.pfp }}></Image>
<View style={mesgStyles.spacer} />
<View style={mesgStyles.messageBody}>
<Text style={mesgStyles.mainText}>{item.text}</Text>
</View>
</View>
);
}
Any help would be greatly appreciated. Thanks

Flatlist scroll and scrollview scroll is not working inside modal

I am making filter modal for e-commerce application where I divided it into two component view one for left and one for right view. Where I am using flatlist for left view and scrollview for right.
I am trying achieve scroll on both side. I don't know why isn't working.Same code is working for different project without any problem.
I am unable to scroll on either side.
Attaching code snippet for same.
<Modal
animationType="slide"
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => {
this.setState({ modalVisible: !this.state.modalVisible });
}}
>
<View style={Style.general.centeredView}>
<View style={Style.general.modalView}>
<View style={Style.general.filterModal}>
<Text style={Style.general.filterModalHeading}>FILTERS</Text>
{this.state.filtersApplied.length > 0 ? (
<TouchableOpacity
style={{
alignSelf: "flex-end",
marginRight: 10,
paddingHorizontal: 10,
paddingVertical: 5,
borderWidth: 1,
borderColor: "#000",
borderRadius: 5,
}}
onPress={() => this.clearFiltersHandler()}
>
<Text>Clear Filters</Text>
</TouchableOpacity>
) : null}
</View>
<View style={Style.general.filterModalData}>
<View style={Style.general.filterModalDataLeftScroll}>
{/* {isFetching && modalVisible ? <Loader /> : null} */}
{this.state.filters && (
<FlatList
// contentContainerStyle={styles.listContainer}
data={this.state.filters}
// numColumns={2}
// onEndReached={() => fetchProducts(false, sortApplied)}
// onEndReachedThreshold={0.1}
keyExtractor={() =>
"_" + Math.random().toString(36).substr(2, 9)
}
renderItem={this.renderFilters}
// removeClippedSubviews
/>
)}
</View>
<ScrollView
style={{
flexGrow: 1,
width: "70%",
flexDirection: "column",
paddingHorizontal: 10,
}}
>
{this.state.activeFilterLabel !== "pf_p_price" &&
this.state.fliterLabel.map((values, i) => {
// console.log("values", values);
return (
<TouchableOpacity
key={i}
onPress={() => this.addFilterHandler(values)}
>
<View
style={Style.general.filterModalDataRightFilter}
>
<View
style={[
Style.general.filterBoxWrap,
{
backgroundColor:
this.state.filtersApplied.some(
(filter) => filter == values.key
)
? "#000"
: "#fff",
},
]}
>
<Icon name="check" size={11} color="#fff" />
</View>
<Text
style={{
fontFamily: "Futura",
fontSize: 12,
}}
>
{values.key}
</Text>
</View>
</TouchableOpacity>
);
})}
{this.state.activeFilterLabel === "pf_p_price" ? (
<View>
<Text>Hello</Text>
</View>
) : null}
</ScrollView>
</View>
{this.state.filterModalLoader ? (
<TouchableOpacity style={{ flex: 1 }} />
) : null}
<View style={Style.general.filterBtnFix}>
<TouchableWithoutFeedback
onPress={() => {
this.setState({ modalVisible: false });
}}
>
<View style={Style.general.filterBtnFixWrap}>
<Text style={Style.general.filterBtnFixWrapText}>
Close
</Text>
</View>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback
onPress={() => {
this.setState({ modalVisible: false });
}}
>
<View style={Style.general.filterBtnFixWrap}>
<Text style={Style.general.filterBtnFixWrapText}>
Apply
</Text>
</View>
</TouchableWithoutFeedback>
</View>
</View>
</View>
</Modal>

React Native TextInput Value persist when Tab is changed

I have encountered a weird issue in the newest react native where the value in the text input in a component remains when a tab is switched.
I can't figure what is going on and I thought it should re-render when tab is changed but it doesn't.
Here's my code
app.js
export default function App() {
const [tab, setTab] = useState("TAB1")
return (
<View style={styles.container}>
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity
style={{ borderRadius: 5, borderWidth: 1, marginRight: 5, padding: 20 }}
onPress={() => setTab("TAB1")}
>
<Text>Tab 1</Text>
</TouchableOpacity>
<TouchableOpacity
style={{ borderRadius: 5, borderWidth: 1, padding: 20}}
onPress={() => setTab("TAB2")}
>
<Text>Tab 2</Text>
</TouchableOpacity>
</View>
<View style={{ marginTop: 20}}>
{
tab === "TAB1" ? (
<View>
<InputComponent tab={tab} />
</View>
) : (
<View>
<InputComponent tab={tab} />
</View>
)
}
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
marginTop: 100,
padding: 10
},
});
inputcomponent.js
export function InputComponent({ tab }) {
const [value, setValue] = useState("");
return (
<View>
<Text>{tab}</Text>
<TextInput placeholder="INPUT HERE" value={value} onChangeText={setValue}/>
</View>
)
}
It seems like the input component re-renders but the text input within it doesn't change.
Demo Issue
This is such a good question. This is because we are importing it once and passing it to two different components. It changes the tab but uses the same textinput state because they are using the same key.
To fix this pass in the key prop so React knows that tab changed:
{
tab === "TAB1" ? (
<View>
<InputComponent key={1} tab={tab} />
</View>
) : (
<View>
<InputComponent key={2} tab={tab} />
</View>
)
}
Snack: https://snack.expo.io/mVVLb9uId
Read about keys: https://reactjs.org/docs/lists-and-keys.html#keys

Automatically scroll ScrollView in KeyboardAvoidingView when I add a new TextInput

I am working with a KeyboardAvoidingView and it's working perfectly fine except for one small issue. In the code below I have a TouchableOpacity that when clicked runs the function addName() which appends to an array and creates a new TextInput - basically when you click it, it adds a new TextInput to the ScrollView.
The KeyboardAvoidingView works perfectly fine except every time a new TextInput is added/rendered, I have to scroll down to see it. Do you know how I can make it automatically scroll to the bottom when a new TextInput is rendered?
Here is my code for the KeyboardAvoidingView:
<KeyboardAvoidingView
style={styles.container}
behavior={Platform.OS == "ios" ? "padding" : "height"}
>
<HeaderComponent
name={this.props.route.params.bill.barName + " Tab"}
navigation={this.props.navigation}
goHome={true}
goHomePrompt={true}
/>
<View
style={{
marginTop: 30,
marginLeft: 10,
}}
>
<Text
style={{ color: "white", fontSize: 18 }}
allowFontScaling={false}
>
Add people to split with...
</Text>
</View>
<ScrollView keyboardShouldPersistTaps={"handled"}>
{this.state.nameInput.map((value, index) => (
<View style={styles.nameContainer} key={index}>
<View
style={{
width: "90%",
}}
>
<TextInput
style={styles.textInputContainer}
value={value}
onChange={this.handleText(index)}
placeholder={"Enter name..."}
placeholderTextColor={"#333333"}
maxLength={50}
/>
</View>
<View
style={{
width: "10%",
}}
>
<TouchableOpacity
onPress={() => this.handleDelete(index)}
>
<Icon name="cancel" type="material" color="red" />
</TouchableOpacity>
</View>
</View>
))}
<TouchableOpacity onPress={() => this.addName()}>
<Text style={styles.addPerson}>+ Add Person</Text>
</TouchableOpacity>
</ScrollView>
<View style={styles.bottomContainer}>
<TouchableOpacity
style={styles.continueButton}
onPress={() => {
// filters through array to make sure there are no empty strings
let nameInput = this.state.nameInput.filter(
(name) => name !== ""
);
if (
nameInput.length > 1 &&
new Set(nameInput).size === nameInput.length
) {
this.setState({ nameInput, loading: false });
} else {
alert(
"Please make sure there are at least two people and no duplicate names!"
);
}
}}
>
<Text style={styles.continueButtonText} allowFontScaling={false}>
Continue to Split Tab
</Text>
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
And here is my code for the addName() function:
addName = () => {
let nameInput = this.state.nameInput.concat("");
this.setState({
nameInput,
});
};
This page has the solution I was looking for: Is it possible to keep a ScrollView scrolled to the bottom?

Different content on React Native based on condition

on my react-native app I would like to have premium content for people who paid a subscription.
My issue is how I make the content to display as unavailable(if you are not premium ) and the same as the other content if you are premium. Basically I would like the premium content to be displayed with a "lock overlay" on it for non-premium users.
However, I do not know how I set this conditional. It is a matter of state? If yes where should be positioned this state considering that is unidirectional?
Just to be clear I will have premium and non premium content
class Browser extends Component {
scrollX = new Animated.Value(0);
renderRecommended = () => {
return (
<View style={[styles.flex, styles.column, styles.recommended]}>
<View style={[styles.row, styles.recommendedHeader]}>
<Text
style={{
fontSize: theme.sizes.font * 1.4,
alignSelf: 'center',
color: 'white',
fontFamily: 'Nunito-Bold',
}}>
Recommended
</Text>
</View>
<View style={[styles.column, styles.recommendedList]}>
<FlatList
horizontal
scrollEnabled
showsHorizontalScrollIndicator={false}
scrollEventThrottle={16}
snapToAlignment="center"
style={[styles.shadow, {overflow: 'visible'}]}
data={this.props.destinations}
keyExtractor={(item, index) => `${item.id}`}
renderItem={({item, index}) =>
this.renderRecommendation(item, index)
}
/>
</View>
</View>
);
};
renderRecommendation = (item, index) => {
const {destinations} = this.props;
const isLastItem = index === destinations.length - 1;
const {navigation} = this.props;
return (
<TouchableOpacity
onPress={() =>
this.props.navigation.navigate('PreScreen', {
item,
})
}>
<View
style={[
styles.flex,
styles.column,
styles.recommendation,
styles.shadow,
index === 0 ? {marginLeft: theme.sizes.margin} : null,
isLastItem ? {marginRight: theme.sizes.margin / 2} : null,
]}>
<ImageBackground
style={[styles.imageback]}
source={{uri: item.preview}}
/>
</View>
<View
style={[
index === 0 ? {marginLeft: theme.sizes.margin - 10} : null,
isLastItem ? {marginRight: theme.sizes.margin / 2} : null,
]}>
<Text
style={{
fontSize: theme.sizes.font * 1.25,
fontWeight: '200',
color: 'white',
marginLeft: 10,
//paddingBottom: 20,
fontFamily: 'Nunito-Bold',
}}>
{item.title}
</Text>
<Text
style={{
color: theme.colors.caption,
marginLeft: 10,
fontFamily: 'Nunito-SemiBold',
}}>
{item.location}
</Text>
</View>
</TouchableOpacity>
);
};
render() {
return (
<ScrollView style={styles.container}>
<BackgroundSvg style={styles.background} />
<ScrollView
style={styles.contentContainer}
showsVerticalScrollIndicator={false}
contentContainerStyle={{paddingBottom: theme.sizes.paddin}}>
{this.renderRecommended()}
{this.renderRecommended2()}
{/* <View style={styles.mainContainerView}>
<TouchableOpacity style={styles.singInButton} gradient>
<Text style={styles.logInText}>
Activate premium subscription
</Text>
</TouchableOpacity>
</View> */}
</ScrollView>
</ScrollView>
);
}
}
Browser.defaultProps = {
destinations: mocks,
reading: readingList,
};
export default Browser;
My code is the one on the top. Just to simplify I am accesing some elements from JSON and I am creating Flatlist based on this. What I want is is to give some of the JSON files a bolean with premium or not and in this way to make some elements available for user or not.
As part of your destinations array, for each object, you can specify a boolean field called isPremiumItem. Your users should have a boolean field like isPremiumUser to show the type of their subscription.
Then in renderRecommended method you can check the user subscription status (isPremiumUser), and also the specific item status (isPremiumItem). Then you can render accordingly.

Categories

Resources