Text is not updating in React Native - javascript

app.js
import { StatusBar } from "expo-status-bar";
import {
TouchableOpacity,
Button,
StyleSheet,
Alert,
SafeAreaView,
Text,
} from "react-native";
export default function App() {
let count = 5;
let counts = [count];
return (
<SafeAreaView style={styles.container}>
<Text style={styles.Text}>Earn Money</Text>
<TouchableOpacity
onPress={() => {
count += 0.25;
console.log(count);
}}
style={{
height: 70,
width: 130,
backgroundColor: "#ff5c5c",
alignSelf: "center",
top: 25,
}}
>
<Text
style={{
fontWeight: "900",
alignSelf: "center",
position: "relative",
top: 25,
}}
>
Earn 0.20$
</Text>
</TouchableOpacity>
<Text style={styles.Balance}>{count}</Text>
<StatusBar style="auto" />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: Platform.OS === "android" ? 90 : 0,
paddingLeft: Platform.OS === "android" ? 10 : 0,
},
Text: {
justifyContent: "center",
alignSelf: "center",
color: "orange",
fontSize: 25,
fontWeight: "900",
},
Balance: {
justifyContent: "center",
alignSelf: "center",
color: "orange",
fontSize: 25,
fontWeight: "900",
top: 100,
},
});
So when I press touchableOpacity the count variable is supposed to add 0.25 to itself , That is working fine but the text
<Text style={styles.Balance}>{count}</Text>
is not updating.I would also want to know if the way I dispaly the variable count in <Text><Text/> is correct.
THe text is just showing 5 I have no prior experience with React native if you would help pls do.

React uses some hooks for updating the DOM you can't just use variables and expect it to update the DOM, in this instance you need to use useState hook
import { StatusBar } from "expo-status-bar";
import { useState} from "react";
import {
TouchableOpacity,
Button,
StyleSheet,
Alert,
SafeAreaView,
Text,
} from "react-native";
export default function App() {
let [count, setCount] = useState(0);
return (
<SafeAreaView style={styles.container}>
<Text style={styles.Text}>Earn Money</Text>
<TouchableOpacity
onPress={() => {
setCount(c => c + 0.5)
}}
style={{
height: 70,
width: 130,
backgroundColor: "#ff5c5c",
alignSelf: "center",
top: 25,
}}
>
<Text
style={{
fontWeight: "900",
alignSelf: "center",
position: "relative",
top: 25,
}}
>
Earn 0.20$
</Text>
</TouchableOpacity>
<Text style={styles.Balance}>{count}</Text>
<StatusBar style="auto" />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: Platform.OS === "android" ? 90 : 0,
paddingLeft: Platform.OS === "android" ? 10 : 0,
},
Text: {
justifyContent: "center",
alignSelf: "center",
color: "orange",
fontSize: 25,
fontWeight: "900",
},
Balance: {
justifyContent: "center",
alignSelf: "center",
color: "orange",
fontSize: 25,
fontWeight: "900",
top: 100,
},
});
You can read this article to better understand react and how it works.

import { useState} from "react";
const [count,setCount]=useState(5) // 5 is default value
const [update,setUpdate]=useState(0) // add this
export default function App() {
let count = 5;
let counts = [count];
return (
<SafeAreaView style={styles.container}>
<Text style={styles.Text}>Earn Money</Text>
<TouchableOpacity
onPress={() => {
count += 0.25;
setCount(count) // add this
setUpdate(update+1) // add this
console.log(count);
}}
style={{
height: 70,
width: 130,
backgroundColor: "#ff5c5c",
alignSelf: "center",
top: 25,
}}
>
<Text
style={{
fontWeight: "900",
alignSelf: "center",
position: "relative",
top: 25,
}}
>
Earn 0.20$
</Text>
</TouchableOpacity>
<Text style={styles.Balance}>{count}</Text>
<StatusBar style="auto" />
</SafeAreaView>
);
}

Related

React-Native 0.68.2 Modals are not working - iOS

I upgraded react native application to react version 17.0.1 and react-native 0.68.2.
Modals are no longer visible on the iOS application beyond that point. I'm using the react-native-modal: "^13.0.1" library to create those modals.
To confirm the issue, I replaced sample modal code react-native-modal-example on top of my existing code. However, the problem is still present.
There is a bug reported like this
Therefore, I used modal provided by react-native instead of using react-native-modal: "^13.0.1" but the same problem is occurred.
Is there any solution for this?
my code as follows,
import React, {useState} from 'react';
import {Image, View, Text, TouchableOpacity, Alert, Pressable, StyleSheet} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import Modal from 'react-native-modal'
const login = props => {
const [modalVisible, setModalVisible] = useState(false);
return (
<SafeAreaView style={styles1.centeredView}>
<Modal isVisible={true}>
<View style={styles1.centeredView}>
<View style={styles1.modalView}>
<Text style={styles1.modalText}>Hello World!</Text>
<Pressable
style={[styles1.button, styles1.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}>
<Text style={styles1.textStyle}>Hide Modal</Text>
</Pressable>
</View>
</View>
</Modal>
<TouchableOpacity
style={[styles1.button, styles1.buttonOpen]}
onPress={() => setModalVisible(true)}>
<Text style={styles1.textStyle}>Show Modal</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
const styles1 = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5
},
button: {
borderRadius: 20,
padding: 10,
elevation: 2
},
buttonOpen: {
backgroundColor: "#F194FF",
},
buttonClose: {
backgroundColor: "#2196F3",
},
textStyle: {
color: "white",
fontWeight: "bold",
textAlign: "center"
},
modalText: {
marginBottom: 15,
textAlign: "center"
}
});
export default (login);
This one works!
import React, { useState } from "react";
import {
Modal,
View,
Text,
TouchableOpacity,
Alert,
Pressable,
StyleSheet,
SafeAreaView
} from "react-native";
const Example = props => {
const [modalVisible, setModalVisible] = useState(false);
return (
<SafeAreaView style={styles1.centeredView}>
<Modal isVisible={true}>
<View style={styles1.centeredView}>
<View style={styles1.modalView}>
<Text style={styles1.modalText}>Hello World!</Text>
<Pressable
style={[styles1.button, styles1.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles1.textStyle}>Hide Modal</Text>
</Pressable>
</View>
</View>
</Modal>
<TouchableOpacity
style={[styles1.button, styles1.buttonOpen]}
onPress={() => setModalVisible(true)}
>
<Text style={styles1.textStyle}>Show Modal</Text>
</TouchableOpacity>
</SafeAreaView>
);
};
export default Example;
const styles1 = StyleSheet.create({
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 4,
elevation: 5
},
button: {
borderRadius: 20,
padding: 10,
elevation: 2
},
buttonOpen: {
backgroundColor: "#F194FF"
},
buttonClose: {
backgroundColor: "#2196F3"
},
textStyle: {
color: "white",
fontWeight: "bold",
textAlign: "center"
},
modalText: {
marginBottom: 15,
textAlign: "center"
}
});

Async Storage movie watchlist in React Native

its my first time i create an APP for my study project , i created app of database of movies using TMDB API , and it remain one last step to finish my project , and it's creating WatchList or Plan to Watch , and i have no idea how to make it . please can someone who have idea of how to create it with Async Storage or anything to save watchlist, and where to add it?
I will put my code
this code of Movie screen, and i need a touchableopacity that make save the movie into favorite component
import React, {useEffect, useState} from 'react';
import {
View,
Text,
Image,
Dimensions,
StyleSheet,
Linking,
ImageBackground,
TouchableOpacity,
ScrollView,
FlatList
} from 'react-native';
import {IMAGE_POSTER_URL} from '../config';
import {GET} from '../../Services/API';
import Loader from '../Components/Loader';
import Constants from '../Components/Constants';
import TrendingMovies from '../Components/TrendingMovies';
import TrendingPeople from '../Components/TrendingPeople';
import { createStackNavigator } from "#react-navigation/stack";
import PeopleDetails from '../Components/PeopleDetails.js';
import { LinearGradient } from 'expo-linear-gradient';
import {POSTER_IMAGE} from '../config';
import AsyncStorage from '#react-native-async-storage/async-storage';
const deviceHeight = Dimensions.get('window').height;
const deviceWidth = Dimensions.get('window').width;
const MovieDetails = props => {
const [loading, setLoading] = useState(true);
const [details, setDetails] = useState();
const [favourites, setFavourites] = useState([]);
useEffect(() => {
const getDetails = async () => {
const data = await GET(`/movie/${props.route.params.movieId}`);
setDetails(data);
setLoading(false);
};
getDetails();
}, []);
useEffect(() => {
const getVideo = async () => {
const results = await GET(`/movie/${props.route.params.movieId/videos}`);
setDetails(results);
setLoading(false);
};
getVideo();
}, []);
const getGenre = () => {
return details.genres.map(genre => (
<View >
<Text style={styles.genre}>{genre.name}</Text>
</View>
));
};
return (
<View style={styles.sectionBg}>
{loading ? (
<Loader />
) : (
<View style={{ flex: 1 }} >
<Image
source={{uri: `${IMAGE_POSTER_URL}${details.backdrop_path}`}}
style={styles.imageBg}
/>
<View style={{flexDirection:'row', justifyContent:'space-between', alignItems:'center', marginRight:15, marginTop:10}}>
<TouchableOpacity onPress={() => props.navigation.goBack()}
style={{ marginLeft:20, marginTop: 20, marginBottom:20}}
>
<Image
source={require("../../assets/icons/back.png")}
style={{ width:93/1.4 , height: 50/1.4 }} />
</TouchableOpacity>
<TouchableOpacity
style={{ marginLeft:20, marginTop: 20, marginBottom:20}}
>
<Image
source={require("../../assets/icons/nolicked.png")}
style={{ width:256/5.7 , height: 252/5.7 }} />
</TouchableOpacity>
</View>
<ScrollView style={{ flex:1 ,}} >
<TouchableOpacity onPress={() => {
Linking.openURL('https://www.youtube.com/watch?v=${details.key}');
}}
style={{ marginTop:240, marginLeft: "70%",zIndex:1 }}
>
<Image
source={require("../../assets/icons/youtube.png")}
style={{ width: 75, height: 75}} />
</TouchableOpacity>
<ImageBackground
source={require("../../assets/icons/hmm.png")}
style={{ width:'100%' , height: '84%',zIndex:-1 ,marginTop: -60,marginBottom:20}} >
<View style={{ alignSelf: 'center' , marginTop:40 }} >
<View style={{flexDirection: 'row' }} >
<Image
source={{uri: `${IMAGE_POSTER_URL}${details.poster_path}`}}
style={{ width: 150/1.2 , height: 220/1.2 , borderRadius: 20, marginTop: 40 , marginLeft: 20, zIndex:1 }} />
<View style= {{flexDirection:'column' , }} >
<Text style={styles.detailsMovieTitle}>{details.title}</Text>
<View style={{flexDirection: 'row' , alignItems: 'center', marginLeft: 15 , backgroundColor:'orange' , width:70, marginVertical: 5, borderRadius:10}} >
<Image
source={require("../../assets/icons/star.png")}
style={{ width: 20, height: 20 , marginLeft: 5, marginVertical:8}} />
<Text style= {{color:'#20222A' , fontSize: 18, marginLeft: 6, fontWeight:'bold' ,marginRight: 15}} >{details.vote_average}</Text>
</View>
<View style={{ flexDirection: 'row', width: 80 ,marginTop:25, marginLeft:20}}>
{getGenre()}
</View>
<Text style={{marginLeft: 14,
marginHorizontal:-5,
marginVertical:5,
fontWeight:'bold',
color: '#C3C3C3',
fontSize: 10,}}>{details.runtime} Minutes</Text>
<Text style={{marginLeft: 14,
marginHorizontal:-5,
color: '#C3C3C3',
fontWeight:'bold',
fontSize: 10,}}> Release Date: {details.release_date} </Text>
</View>
</View>
<View style={{marginLeft:15, zIndex:1 , marginBottom:50, marginLeft:20}} >
<Text style={{color:'white', fontSize:16, fontWeight:'bold' , marginBottom: 1,marginLeft: -5}} > Overview </Text>
<Text style={{color: 'white',
fontSize: 12, width:330, marginBottom:15}}>{details.overview}</Text>
<TrendingPeople
title="Actors"
navigation={props.navigation}
url={`/movie/${props.route.params.movieId}/credits`}
isForPage="details"
/>
<View style={{marginLeft: -15, marginTop:10, }} >
<TrendingMovies
title="SIMILAR MOVIES"
navigation={props.navigation}
url={`/movie/${props.route.params.movieId}/similar`}
/>
</View>
</View>
</View>
</ImageBackground>
</ScrollView>
</View>
)}
</View>
);
};
const styles = StyleSheet.create({
sectionBg: {
backgroundColor: Constants.baseColor,
height: deviceHeight,
flex:1
},
trendingPeopleImage: {
height: 70,
width: 70,
borderRadius: 500,
},
trendingPeopleName: {
width: 60,
color: Constants.textColor,
fontSize: 12,
textAlign: 'center',
marginTop: 10,
},
trendingPeopleContainer: {
margin: 10,
},
heading: {
fontSize: 12,
color: 'white',
margin: 10,
fontWeight:'bold'
},
posterImage: {
height: 800,
width: 150,
borderRadius: 10,
},
movieTitle: {
color: Constants.textColor,
width: 150,
textAlign: 'center',
marginTop: 5,
fontSize: 20,
fontWeight:'bold'
},
imageBg: {
position: 'absolute', top:0, left:0 ,
width: deviceWidth,
height: 400,
opacity: 0.8
},
detailsMovieTitle: {
fontSize: 20,
width: 180,
fontWeight:'bold',
color: 'white',
marginLeft:15,
marginTop: 35
},
linkContainer: {
backgroundColor: Constants.secondaryColor,
borderRadius: 100,
padding: 10,
width: 45,
marginLeft: 20,
marginTop: -20,
},
overview: {
color: 'white',
marginHorizontal: 10,
textAlign: 'justify',
fontSize: 16,
},
details: {
color: 'white',
fontSize: 11,
marginLeft: 10,
fontWeight: 'bold',
},
detailsContainer: {
display: 'flex',
marginLeft:15
},
genreContainer: {
borderColor: Constants.textColor,
paddingHorizontal: 0,
},
genre: {
width: 50,
marginHorizontal:-5,
fontWeight:'bold',fontWeight:'bold',
color: '#C3C3C3',
marginRight:4,
fontSize: 9,
},
image : {
height: 100,
width: 180,
borderRadius: 15,
paddingHorizontal: 5,
marginTop: 10,
marginLeft: 20
},
Text: {
marginLeft: 20,
color: 'white',
fontWeight: 'bold',
fontSize: 20
},
title: {
marginTop: 10,
width: 150,
textAlign: 'center',
color: 'white',
fontWeight: 'bold',
fontSize: 12
}
});
export default MovieDetails;```
First you create a favorite state
const [ favorites, setFavorites ] = useState([]);
Then you use useEffect to load the favorite from async storage.
const getData = async () => {
try {
const value = await AsyncStorage.getItem('#storage_key')
if(value !== null) {
setFavorites(JSON.parse('#storage_key'));
}
} catch(e) {
// error reading value
}
}
useEffect(() => {
getData();
}, [])
Then you create a touchable component to add to favorites.
<TouchableOpacity onPress={() => addToFavorites('some_id')}>
Add to Favorites
</TouchableOpacity>
Create the add to favorite function
const addToFavorites = async (id) => {
await AsyncStorage.setItem('#storage_key', JSON.stringify([...favorites, id]))
setFavorites([...favorites, id]);
}
More on Asyncstorage usage here - https://react-native-async-storage.github.io/async-storage/docs/usage

Error : undefined is not an object (evaluating 'source')

I'm using WordPress API in my react native app. Everything is working fine except my single post screen. I'm requesting post data, updating state, and rendering data from the state. My app was crashing after going on this screen. I spend hours and I've found out what's the problem however don't how to fix it.
My Screen Code -
import React, { useState, useEffect } from "react";
import {
ActivityIndicator,
Text,
View,
ScrollView,
Image,
useWindowDimensions,
} from "react-native";
import HTMLView from "react-native-htmlview";
import globalStyles from "../constant/globalStyle";
import axios from "axios";
import moment from "moment";
import { Colors } from "../constant/colors";
const PostDetail = ({ route }) => {
const { postId } = route.params;
const [postData, setPostData] = useState({});
const [loaded, setLoaded] = useState(false);
const [source, setSource] = useState("");
useEffect(() => {
const fetchData = async () => {
await axios
.get(
`https://bachrasouthpanchayat.in/wp-json/wp/v2/posts/${postId}?embed=true`
)
.then((response) => {
setPostData(response.data);
setSource(response.data.content.rendered);
setLoaded(true);
})
.catch((error) => console.log(error, error.message));
};
fetchData();
}, []);
const { width } = useWindowDimensions();
return (
<ScrollView
style={{
...globalStyles.container,
backgroundColor: Colors.BACKGROUND_SCREEN,
}}
>
{loaded ? (
<>
<Image
style={{
width: "100%",
height: 250,
}}
source={{ uri: postData.jetpack_featured_media_url }}
resizeMode="cover"
/>
<Text style={globalStyles.primaryHeading}>
{postData.title.rendered}
</Text>
<View style={{ paddingHorizontal: 18 }}>
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 10,
}}
>
<Text
style={{
...globalStyles.date,
fontSize: 20,
fontWeight: "700",
}}
>
{moment(postData.date).format("LL")}
</Text>
</View>
<HTMLView
stylesheet={{
p: { fontSize: 20, color: "white", textAlign: "justify" },
h1: {
color: "white",
fontSize: 32,
},
h2: {
color: "white",
fontSize: 28,
},
figure: {
backgroundColor: "red",
width: "100% !important",
height: "100% !important",
},
img: {
width: "100% !important",
backgroundColor: "green",
},
}}
value={source}
imagesMaxWidth={width}
/>
</View>
</>
) : (
<View
style={{
alignItems: "center",
justifyContent: "center",
}}
>
<ActivityIndicator size={60} color={Colors.PRIMARY_GREEN} />
</View>
)}
</ScrollView>
);
};
export default PostDetail;
I've used a bunch of console log statements and found out that "when useEffect runs the request is sent to API but it didn't stay on that line of code to receive a response, instead remaining lines of codes are executed and that's why I was getting the undefined error". However, the state gets updated after some time but I still get the error.
I have used async & await but don't know why all those remaining lines of codes ran before getting a response.
When this page is rendered for the first time, your postData is an empty object:
const [postData, setPostData] = useState({});
and at this point of time you try to access it's children (but it doesn't have them yet):
<Text style={globalStyles.primaryHeading}>
{postData.title.rendered} // here you access the empty object
</Text>
Then the useEffect is called which populates that postData
The solution (just add the question mark after postData.title?.rendered):
<Text style={globalStyles.primaryHeading}>
{postData.title?.rendered}
</Text>
The better solution is to show loading until you have not fetched the component:
if(postData.title?.rendered)
return <ActivityIndicator size={24} color={"#424242"} />
return (
<ScrollView
style={{
...globalStyles.container,
backgroundColor: Colors.BACKGROUND_SCREEN,
}}
>
{loaded ? (
<>
<Image
style={{
width: "100%",
height: 250,
}}
source={{ uri: postData.jetpack_featured_media_url }}
resizeMode="cover"
/>
<Text style={globalStyles.primaryHeading}>
{postData.title.rendered}
</Text>
<View style={{ paddingHorizontal: 18 }}>
<View
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
marginBottom: 10,
}}
>
<Text
style={{
...globalStyles.date,
fontSize: 20,
fontWeight: "700",
}}
>
{moment(postData.date).format("LL")}
</Text>
</View>
<HTMLView
stylesheet={{
p: { fontSize: 20, color: "white", textAlign: "justify" },
h1: {
color: "white",
fontSize: 32,
},
h2: {
color: "white",
fontSize: 28,
},
figure: {
backgroundColor: "red",
width: "100% !important",
height: "100% !important",
},
img: {
width: "100% !important",
backgroundColor: "green",
},
}}
value={source}
imagesMaxWidth={width}
/>
</View>
</>
) : (
<View
style={{
alignItems: "center",
justifyContent: "center",
}}
>
<ActivityIndicator size={60} color={Colors.PRIMARY_GREEN} />
</View>
)}
</ScrollView>

horizontal ScrollView is not scrolling

When adding horizontal={true} to my scrollview, I thought that would be enough to be able to scroll sideways. For some reason, even though there is enough content to scroll to, the images will not scroll continuously. If you copy and paste this code into snack.expo.io you will see what I mean.
I am not sure what is causing this issue, as I know the normal scrollview vertically works fine and scrolls like normal. I have also tried using nestedScrollenabled to true
Any insight at all is appreciated more than you know!
import React, { useState } from 'react';
import {Pressable, StyleSheet, Text, View, useWindowDimensions, Dimensions, Image, Animated, PanResponder,
TouchableOpacity, ScrollView, ImageBackground, Platform} from 'react-native';
import { SearchBar } from 'react-native-elements';
import {
scale,
verticalScale,
moderateScale,
ScaledSheet,
} from 'react-native-size-matters';
import { MaterialCommunityIcons } from '#expo/vector-icons';
const Images = [
{ id: '1', uri: require('./assets/snack-icon.png'), text: 'Test' },
{ id: '2', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
{ id: '3', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
{ id: '4', uri: require('./assets/snack-icon.png') /*text: "Test"*/ },
]
const pressableTest = () => {
let textlog = '';
const [state, setState] = useState(0);
};
export default class Home extends React.Component {
renderImagesHorizontal = () => {
return Images.map((item, i) => {
return (
<View
style={{
width : '150%',
paddingLeft: scale(10),
paddingRight: scale(10),
paddingBottom: scale(15),
}}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('VenueDetails')}>
<ImageBackground
source={item.uri}
style={{
width: '100%',
height: scale(225),
shadowColor: '#000',
shadowOffset: { width: 1, height: 4 },
shadowOpacity: 1,
}}
imageStyle={{ borderRadius: 10 }}>
<View
style={{
position: 'absolute',
bottom: 10,
left: 10,
justifyContent: 'flex-start',
alignItems: 'flex-start',
}}>
<Text style={styles.name}>Name</Text>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={styles.category}>Category</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.money}>$$</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.starRating}>★★★</Text>
</View>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
);
});
};
renderImagesVertical = () => {
return Images.map((item, i) => {
return (
<View style={{ paddingLeft: scale(10), paddingRight: scale(10), paddingBottom: scale(20) }}>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('VenueDetails')}>
<ImageBackground
source={item.uri}
style={{ width:'100%', height: scale(125),
shadowColor: '#000',
shadowOffset: {width: 1, height: 7},
shadowOpacity: 1,}} imageStyle = {{ borderRadius: 20}}>
<View
style={{
position: 'absolute',
bottom: 10,
left: 10,
justifyContent: 'flex-start',
alignItems: 'flex-start',
}}>
<Text style={styles.name}>Name</Text>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<Text style={styles.category}>Category</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.money}>$$</Text>
<Text style={styles.dot}>⬤</Text>
<Text style={styles.starRating}>★★★</Text>
</View>
</View>
</ImageBackground>
</TouchableOpacity>
</View>
);
});
};
state = {
search: '',
};
updateSearch = (search) => {
this.setState({ search });
};
render() {
const { search } = this.state;
return (
<ScrollView style={{ flex: 1, backgroundColor: '#272933', horizontal: 'true' }}>
<View style={{flexDirection:'row', marginTop: scale(20)}}>
{/*this will proabbly say somethign different and probably have a different look to it but you get the idea
I was also trying to add a shadow to this but couldnt figure it out. */}
<Text style={{marginTop: scale(30) ,fontSize: scale(40), fontWeight: 'bold', color: '#FFFFFF', paddingLeft: scale(20)}}>
Home
</Text>
<View style={{paddingTop: scale(40), paddingLeft: scale(155)}}>
</View>
</View>
<SearchBar
placeholder="Search..."
onChangeText={this.updateSearch}
value={search}
round='true'
containerStyle={{backgroundColor: '#272933', borderBottomColor: 'transparent', borderTopColor: 'transparent',
paddingLeft: scale(20) , paddingRight: scale(20)}}
inputContainerStyle={{height: scale(30), width: scale(310), backgroundColor: '#3A3B3C'}}
searchIcon={() => <MaterialCommunityIcons name="glass-mug-variant" size={25} color='#87909A'/>}
clearIcon= 'null'
/>
<ScrollView
horizontal={true}
>
<View style={{ flex: 1, flexDirection : 'row', marginTop: 15 }}>{this.renderImagesHorizontal()}</View>
</ScrollView>
<View style={{ flex: 1, marginTop: 15 }}>{this.renderImagesVertical()}</View>
</ScrollView>
);
}
}
const styles = ScaledSheet.create({
starRating: {
color: 'white',
fontSize: '20#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
category: {
color: 'white',
fontSize: '20#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
name: {
fontWeight: 'bold',
color: 'white',
fontSize: '25#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
dot: {
color: 'white',
fontSize: '5#s',
paddingLeft: '5#s',
paddingRight: '5#s',
textShadowOffset: { width: 2, height: 2 },
textShadowRadius: 2,
textShadowColor: '#000',
},
money: {
color: 'white',
fontSize: '20#s',
},
});
in android you must add nestedScrollEnabled={true} to Enables nested scrolling for Android API level 21+. see here
<ScrollView>
<ScrollView nestedScrollEnabled={true}>
</ScrollView>
</ScrollView>
try snack here (test in android & ios not web)

react native : How can TouchableOpacity be displayed or hidden according to the conditions?

How can TouchableOpacity be displayed or hidden according to the conditions?
How TouchableOpacity can be viewed or hidden depending on the conditions
Only if the Sampling_Method_Description field is not null then TouchableOpacity should be displayed otherwise not displayed.
<TouchableOpacity
style={{
height: 50,
width: 50,
borderRadius: 5,
borderColor: 'black',
borderWidth: 2,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'red',
left: 120,
top: 7,
}}
onPress={() => {
console.log('EYE PRESSED!!')
}}
>
<MaterialIcons
size={40}
name='visibility'
/>
</TouchableOpacity>
You can use ternary operator inside JSX block like so:
return (
<View>
{yourConditionIsTrue?
<TouchableOpacity
style={{
height: 50,
width: 50,
borderRadius: 5,
borderColor: 'black',
borderWidth: 2,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'red',
left: 120,
top: 7,
}}
onPress={() => {
console.log('EYE PRESSED!!')
}}
>
<MaterialIcons
size={40}
name='visibility'
/>
</TouchableOpacity>
:
null }
</View>
)
import React, {useState} from "react";
import { View } from "react-native";
Example = () => {
const [showButton, setshowButton] = useState(false);
const renderButton = () => {
return showButton ? (
<TouchableOpacity
style={{
height: 50,
width: 50,
borderRadius: 5,
borderColor: "black",
borderWidth: 2,
alignItems: "center",
justifyContent: "center",
backgroundColor: "red",
left: 120,
top: 7,
}}
onPress={() => {
console.log("EYE PRESSED!!");
}}>
<MaterialIcons size={40} name="visibility" />
</TouchableOpacity>
) : null;
};
return <View>{renderButton()}</View>;
};
You can simply use the && operator :
{Sampling_Method_Description &&
<TouchableOpacity
//other props
//...
//...
/>}

Categories