React Native change integer value when button is kicked - react-native

I am having a problem changing an integer value, the code below is showing a list of item, and control how many items will be shown when the button is clicked
The variable I want to change when it is clicked,
var showdata = 5;
code for the button and want to change it to 10 when clicked, also want the text change to Less, and showdata change back to 5 when it is for the second time
<View style={externalStyle.more_buttom}>
<TouchableOpacity onPress={() => showdata == 10}>
<Text
style={{
fontWeight: "bold",
fontSize: 13,
color: "#FFF",
}}
>
More{" "}
</Text>
</TouchableOpacity>
</View>
code for the list of item, show data used at "topTen.slice"
<ScrollView
vertical
showsHorizontalScrollIndicator={false}
style={{ paddingBottom: 0 }}
>
{isLoadingTopTen ? (
<Text
style={{
fontWeight: "bold",
fontSize: 13,
color: "#FFF",
textAlign: "center",
}}
>
Loading top ten
</Text>
) : (
topTen
.slice(0, showdata)
.map((item, index) => (
<InfoCard
navigation={navigation}
brand={item.Name}
amount={item.esgrating}
key={index}
/>
))
)}
</ScrollView>

Use useState hooks for changing the value of showData.
const [showdata, setShowData] = useState(5)
//..........
<View style={externalStyle.more_buttom}>
<TouchableOpacity onPress={() => setShowdata(10)}>
<Text
style={{
fontWeight: "bold",
fontSize: 13,
color: "#FFF",
}}
>
More{" "}
</Text>
</TouchableOpacity>
</View>
Working Example: Expo Snack
import React, { useState } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
import Constants from 'expo-constants';
export default function App() {
const [showdata, setShowData] = useState(5);
return (
<View style={styles.container}>
<TouchableOpacity
onPress={() => {
setShowData(10);
}}>
<View style={{ backgroundColor: 'pink', padding: 10 }}>
<Text
style={{
fontWeight: 'bold',
fontSize: 13,
color: '#000',
}}>
More {showdata}
</Text>
</View>
</TouchableOpacity>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
padding: 8,
},
});

Related

How to make TouchableOpacity image look like pressed in?

I have an image in each TouchableOpacity and I would like to change the picture in every onPress function so she could looked like shes pressed in (for example: remove the color from to picture and changes it to black and white or make a light gray shadow on the picture ).
and Reverse (when you click shes changing back to the original picture (Press:true/false).
I have a stateless Component and no class.
My Component :
export default function Recipie({ navigation, route }) {
const recipies = GetRecipies();
return (
<View style={{ flexGrow: 1, flex: 1 }}>
<ScrollView>
{recipies.map((u, i) => {
return (
<View key={i}>
<Text
onPress={navigation.navigate}
style={{
fontSize: 25,
fontFamily: "Cochin",
textAlign: "center",
}}
>
{u._recipieName}
</Text>
<TouchableOpacity
onPress={() => {
navigation.navigate("SingleRecipieScreen", { u });
}}
>
<Image
style={{
height: 200,
width: 350,
borderRadius: 80,
alignSelf: "center",
}}
source={{ uri: u._imgUrl }}
/>
</TouchableOpacity>
<Text
style={{
fontSize: 17,
fontFamily: "Cochin",
textAlign: "center",
}}
>
{u._recipieDescription}
</Text>
<TouchableOpacity
style={{ flex: 1, flexDirection: "column", flexGrow: 1 }}
>
{Show(u._preparationTime)}
</TouchableOpacity>
</View>
);
})}
</ScrollView>
</View>
);
}
Try to use position absolute in View to cover button , and useState for styles, example :
import React, { useState } from "react";
import { StyleSheet, Text, TouchableOpacity, View,Image } from "react-native";
const App = () => {
const [isPressed, setIsPressed] = useState(0);
const onPress = () => setIsPressed(!isPressed);
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.button}
onPress={onPress}
>
<View style={isPressed && styles.pressedButtonStyle} />
<Text> {isPressed ? "Pressed" : " Press Here"}</Text>
<Image
style={ styles.tinyLogo}
source={{
uri: 'https://reactnative.dev/img/tiny_logo.png',
}}
/>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
paddingHorizontal: 10,
},
button: {
alignItems: "center",
backgroundColor: "#DDDDDD",
},
tinyLogo: {
width: 50,
height: 50,
},
pressedButtonStyle: {
position:"absolute",
width:"100%",
height:"100%",
backgroundColor:'black',
opacity:0.6,
zIndex:100,
}
});
https://snack.expo.dev/ixeOwAg3o

How to scroll To next item on a button click using FlatList in React Native?

I have an array of months which I am using to display months using a horizontal FlatList. I want the months to change using 2 buttons that are forward button to change the month in increasing order i.e from January to February and so on and a back button to change the month backwards i.e from January to December.
How can I make the buttons do so. Below monthName is an array that contains all the month names.
<ScrollView style={{flexGrow: 1}}>
<View style={{flex: 1, backgroundColor: '#fff', height: hp('130')}}>
<View
style={{
justifyContent: 'space-evenly',
width: wp('48'),
}}>
<FlatList
data={monthName}
pagingEnabled={true}
showsHorizontalScrollIndicator={false}
renderItem={(month, index) => (
<View>
<Months
showMonth={month.item}
id={month.id}
refer={flatRef}
/>
</View>
)}
keyExtractor={(item, index) => item.id.toString()}
horizontal
// snapToInterval={Dimensions.get('window').width}
snapToAlignment={'center'}
ref={(node) => (flatRef = node)}
/>
</View>
<View
style={{
justifyContent: 'space-evenly',
width: wp('12'),
}}>
{/* {} */}
<IonIcons.Button --> the button that makes the month increment.
name="arrow-forward"
size={25}
backgroundColor="white"
color="black"
// onPress={() => console.log('pressed')}
onPress={() => {
flatRef.scrollToIndex({index: ?});
}}
/>
</View>
</View>
</ScrollView>
try to access ref using current and it should work
this.flatRef.current.scrollToIndex({index: monthName.length > this.state.currentindex ? this.state.currentindex++ : this.state.currentindex });
import React, { useRef } from 'react';
import {
FlatList,
StyleSheet,
Text,
TouchableOpacity,
View
} from 'react-native';
import { wp } from '../../constants/scaling';
import { colors } from '../../constants/theme';
import bookingprocess from '../../data/BookingProcess';
import { textStyles } from '../../styles/textStyles';
import { RFValue } from 'react-native-responsive-fontsize';
import AntDesign from 'react-native-vector-icons/AntDesign';
const BookingProcess = ({}) => {
const flatListRef = useRef(FlatList);
const nextPress = index => {
if (index <= 2) {
flatListRef?.current?.scrollToIndex({
animated: true,
index: index + 1
});
}
};
const backPress = index => {
if (index >= 1) {
flatListRef?.current?.scrollToIndex({
animated: true,
index: index - 1
});
}
};
return (
<View
style={{
...styles.cardView,
padding: 0,
elevation: 0,
borderWidth: 1,
borderColor: '#f2f2f2',
overflow: 'hidden'
}}>
<View
style={{
padding: wp(2),
backgroundColor: colors.primaryColor
}}>
<Text
style={{
...textStyles.heading,
color: '#fff'
}}>
Booking Process
</Text>
</View>
<Text
style={{
...textStyles.mediumheading,
padding: wp(2),
paddingBottom: 0
}}>
You can reserve your parking slot in advance. Please follow
these four simple steps to book your parking slot.
</Text>
<FlatList
data={bookingprocess}
horizontal={true}
ref={flatListRef}
contentContainerStyle={{ padding: wp(2) }}
showsHorizontalScrollIndicator={false}
keyExtractor={(item, index) => item.id}
renderItem={({ item, index }) => {
return (
<View style={styles.innerCard}>
{item.image}
<View style={styles.ButtonBox}>
<TouchableOpacity
onPress={() => backPress(index)}
style={{
backgroundColor: colors.secondaryColor,
borderRadius: wp(50)
}}>
<AntDesign
name="leftcircle"
size={RFValue(25)}
color={colors.primaryColor}
/>
</TouchableOpacity>
<TouchableOpacity
onPress={() => nextPress(index)}
style={{
backgroundColor: colors.secondaryColor,
borderRadius: wp(50)
}}>
<AntDesign
name="rightcircle"
size={RFValue(25)}
color={colors.primaryColor}
/>
</TouchableOpacity>
</View>
<View style={styles.innercardHeaderView}>
<Text style={styles.headingTextNumber}>
{item.id}. {item.title}
</Text>
</View>
<Text style={styles.description}>
{item.description}
</Text>
</View>
);
}}
/>
</View>
);
};
export default BookingProcess;
const styles = StyleSheet.create({
cardView: {
backgroundColor: colors.white,
margin: wp(2),
elevation: 4,
borderRadius: wp(2),
padding: wp(2),
width: wp(94)
},
innerCard: {
margin: wp(2),
borderRadius: wp(2),
padding: wp(0),
paddingTop: 0,
paddingHorizontal: 0,
overflow: 'hidden',
width: wp(90),
elevation: 5,
marginLeft: 0,
padding: wp(2),
backgroundColor: '#fff'
},
ButtonBox: {
position: 'absolute',
flexDirection: 'row',
right: 0,
justifyContent: 'space-between',
width: wp(20),
padding: wp(2)
},
innercardHeaderView: {
backgroundColor: '#0000',
flexDirection: 'row',
padding: wp(2),
paddingBottom: 0,
alignItems: 'center'
},
headingTextNumber: {
...textStyles.heading,
color: colors.primaryColor,
textAlign: 'center',
alignSelf: 'center',
textAlignVertical: 'center'
},
description: {
...textStyles.mediumheading,
paddingHorizontal: wp(2),
textAlign: 'justify'
}
});
Instead of using a FlatList I would suggest you to make a state variable and execute it like this
Working example - Here
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import { AntDesign } from '#expo/vector-icons';
...
const [SelectMonth, SetSelectMonth] = React.useState(monthName[0]);
const NextPress = () => {
if (SelectMonth.id !== 12) {
let temp = monthName.find((c) => c.id === SelectMonth.id + 1);
if (temp) {
SetSelectMonth(temp);
}
}
};
const PrevPress = () => {
if (SelectMonth.id !== 1) {
let temp = monthName.find((c) => c.id === SelectMonth.id - 1);
if (temp) {
SetSelectMonth(temp);
}
}
};
return (
<View style={styles.container}>
<View style={styles.CalenderBox}>
<AntDesign
name="caretleft"
size={30}
color="black"
onPress={() => PrevPress()}
/>
<View style={styles.MonthNameBox}>
<Text style={{ fontWeight: 'bold', fontSize: 24 }}>
{SelectMonth.name}
</Text>
</View>
<AntDesign
name="caretright"
size={30}
color="black"
onPress={() => NextPress()}
/>
</View>
</View>
);

My React Native modal isn't working and I can't find why

I'm not great with react native, and I'm having trouble getting a modal to pop up. It's meant to be like a warning, and then you click the button "I understand" to continue. Thanks, in the future :D
I've been following a tutorial on how to make a React Native app when I get stuck on something, but this part I wasn't able to find an answer. I'm relatively new to react native, and this is my first attempt on creating an app. It would be great to get help :)
Here's what I have so far (app.js is the only file I have yet):
import React, { useState } from 'react';
import { Button, Modal, SafeAreaView, StyleSheet, Text, TouchableOpacity, TouchableWithoutFeedback, View } from 'react-native';
export default function App() {
const [modalVisible, setModalVisible] = useState(false);
return (
<>
<SafeAreaView style={styles.container}>
<TouchableOpacity style={styles.topButton}>
<Text style={styles.text}>
Favorites
</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => setModalVisible(true)} style={styles.button}>
<Text style={styles.text}>
Memes
</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button}>
<Text style={styles.text}>
Jokes
</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button}>
<Text style={styles.text}>
Yo Mama Jokes
</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.button}>
<Text style={styles.text}>
Cute Pictures
</Text>
</TouchableOpacity>
<Modal
visible={modalVisible}
animationType="fade">
style={styles.modal}
<Button title="I understand" visible={modalVisible} onPress={() => setModalVisible(false)}/>
</Modal>
<StatusBar style="auto" />
</SafeAreaView>
</>
);
}
const styles = StyleSheet.create({
container: {
flex: 10,
backgroundColor: '#0f0117',
},
topButton: {
backgroundColor: "dodgerblue",
borderRadius: 15,
alignContent: 'center',
alignItems: 'center',
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 10,
paddingRight: 10,
marginTop: 10,
marginBottom: 50,
marginLeft: 10,
marginRight: 10,
},
button: {
backgroundColor: "dodgerblue",
borderRadius: 15,
alignContent: 'center',
alignItems: 'center',
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 10,
paddingRight: 10,
marginTop: 10,
marginBottom: 10,
marginLeft: 10,
marginRight: 10,
},
text: {
color: '#ffffff',
fontSize: 30,
},
modal: {
backgroundColor: "#0f0117",
marginTop: 15,
marginBottom: 15,
marginLeft: 15,
marginRight: 15,
},
});**
Replace your modal code with this one
<Modal
visible={modalVisible}
animationType="fade"
style={styles.modal}>
<Button title="I understand" visible={modalVisible} onPress={() => setModalVisible(false)}/>
</Modal>
Also you forgot to import StatusBar from react-native.
It may have something to do with your styling. For styles.modal, try
modal: {
backgroundColor: "#0f0117",
marginTop: 15,
marginBottom: 15,
marginLeft: 15,
marginRight: 15,
position: "absolute"
top: "20%" # You can try different values here along with bottom, left, and right properties
},

child component overflow from parent component

import React, {Component} from 'react';
import {Modal, Text, TouchableHighlight, View, Alert} from 'react-native';
export default class AlertModal extends Component {
constructor(props){
super(props)
this.state={
check:'234',
primaryColor:'#dcdcdc',
secondaryColor:'#ff1493',
fontFamily:'sans-serif',
one:'Alert',
two:'sample text'
}
}
state = {
modalVisible: false,
};
setModalVisible(visible) {
this.setState({modalVisible: visible});
}
render() {
return (
<Modal
animationType="slide"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View
style={{
top:'39%',
backgroundColor:this.state.primaryColor,
height:'25%',
width:'70%',
alignSelf:'center'
}}>
<Text
style={{
fontWeight:'500',
fontFamily:this.state.fontFamily,
alignSelf:'center',
fontSize:30,
color:this.state.secondaryColor
}}>
{this.state.one}
</Text>
<View
style={{
borderBottomColor: 'black',
borderBottomWidth: 1,
top:'3%'
}}
/>
<Text
style={{
fontFamily:this.state.fontFamily,
alignSelf:'center',
color:this.state.secondaryColor,
top:'100%'
}}>
{this.state.two}
</Text>
</View>
</Modal>
);
}
}
I am trying to create a new Modal, when I try position last text element 'sample two' in modal component within View, I am failing. 'sample two' is displayed outside of view. I will post the screenshot of what I am getting
but I the need the sample text to be within the end of the box, I don't know why it is displayed outside of the box.
Just wrap it inside another view as shown below.
render() {
return (
<Modal
animationType="slide"
transparent={false}
visible={!this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View
style={{
top: '39%',
backgroundColor: this.state.primaryColor,
height: '25%',
width: '70%',
alignSelf: 'center',
borderWidth: 1,
borderColor: 'red',
}}>
<Text
style={{
fontWeight: '500',
fontFamily: this.state.fontFamily,
alignSelf: 'center',
fontSize: 30,
color: this.state.secondaryColor,
}}>
{this.state.one}
</Text>
<View
style={{
borderBottomColor: 'black',
borderBottomWidth: 1,
top: '3%',
}}
/>
<View>
<Text
style={{
fontFamily: this.state.fontFamily,
alignSelf: 'center',
color: this.state.secondaryColor,
top: '100%',
}}>
{this.state.two}
</Text>
</View>
</View>
</Modal>
);
}
top: '100%', is moving the Text out, change it to 50%
<Text
style={{
fontFamily: this.state.fontFamily,
alignSelf: 'center',
color: this.state.secondaryColor,
top: '50%',
}}>
{this.state.two}
</Text>

React-native TouchableOpacity button doesn't respect border/border-radius

I have created a generic button which I'd like to have round edges instead of being a square. My button component is as such:
const Button = ({ onPress, children }) => {
const { buttonStyle, textStyle } = styles;
return (
<TouchableOpacity onPress={onPress} style={buttonStyle}>
<Text style={textStyle}>
{children}
</Text>
</TouchableOpacity>
);
};
const styles = {
textStyle: {
alignSelf: 'center',
color: colors.primaryTeal,
fontSize: 16,
fontWeight: '600',
paddingTop: 10,
paddingBottom: 10,
},
buttonStyle: {
flex: 1,
backgroundColor: colors.whiteText,
marginLeft: 5,
marginRight: 5,
borderRadius: 50
}
};
However, it remains to be square and doesn't respond to borderRadius at all.
It's invoked as such:
<Button onPress={this.onButtonPress.bind(this)}>
Log in
</Button>
How do I make it respect borderRadius and get round edges?
The login form in which it appears(Render)
render() {
return (
<Card>
<CardSection>
<Input
placeholder="user#gmail.com"
label="Email"
value={this.state.email}
onChangeText={email => this.setState({ email })}
/>
</CardSection>
<CardSection>
<Input
secureTextEntry
placeholder="password"
label="Password"
value={this.state.password}
onChangeText={password => this.setState({ password })}
/>
</CardSection>
<View style={styles.btnWrapper}>
<CardSection>
{this.state.loading ?
<Spinner size="small" /> :
<Button onPress={this.onButtonPress.bind(this)}>
Log in
</Button>}
</CardSection>
</View>
<Text style={styles.errorTextStyle} disabled={this.state.error !== null}>
{this.state.error}
</Text>
</Card>
CardSection component:
const CardSection = (props) => {
return (
<View style={styles.containerStyle}>
{props.children}
</View>
);
};
const styles = {
containerStyle: {
borderBottomWidth: 1,
padding: 5,
backgroundColor: '#fff',
justifyContent: 'flex-start',
flexDirection: 'row',
borderColor: '#ddd',
position: 'relative'
}
};
Works perfectly fine. Just make sure to use react native's StyleSheet.create to get cached styles.
Maybe your button container view background is white and you're not seeing the rounded corners.
Heres my working snack
Code snippet i used, but refer to the snack as you'll see it live in action.
import React, { Component } from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';
const Button = ({ onPress, children }) => {
return (
<TouchableOpacity onPress={onPress} style={styles.buttonStyle}>
<Text style={styles.textStyle}>
{children}
</Text>
</TouchableOpacity>
);
};
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Button>
Log in
</Button>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
backgroundColor: 'black',
},
textStyle: {
alignSelf: 'center',
color: 'teal',
fontSize: 16,
fontWeight: '600',
paddingTop: 10,
paddingBottom: 10,
},
buttonStyle: {
flex: 1,
backgroundColor: 'white',
marginLeft: 5,
marginRight: 5,
borderRadius: 50
},
});
You have to add style overflow: hidden to TouchableOpacity
Try add attribute borderWidth and borderColor on buttonStyle, like below:
buttonStyle: {
backgroundColor: colors.whiteText,
marginLeft: 5,
marginRight: 5,
borderRadius: 50,
borderWidth: 2,
borderColor: "#3b5998"
}
A complete example:
<TouchableOpacity
onPress={() => handleSubmit()}
disabled={!isValid}
style={{
alignSelf: "center",
marginBottom: 30,
overflow: 'hidden',
borderColor: "#3b5998",
borderWidth: 2,
borderRadius: 100,
}}
>
<View
style={{
flexDirection: "row",
alignSelf: "center",
paddingLeft: 15,
paddingRight: 15,
minHeight: 40,
alignItems: 'center',
}}
>
<Text style={{ fontSize: 20, fontWeight: "bold", color: "#3b5998" }}>
SEND
</Text>
</View>
</TouchableOpacity>
I think you might be looking for the containerStyle prop
<TouchableOpacity containerStyle={ViewStyleProps}>