Actually I want to do something like that (Image attached):
There have a box, and two buttons. If I press button 1 then the box moved left. And if I press button 2 then the box moved right.
I want, when the box move right and overcome the bar 1 then the box moved down on the bar 2.
But I have no idea how to do it.
Here is my code:
import React, {Component} from 'react';
import {
View,
Text,
StyleSheet,
Animated,
TouchableOpacity,
ScrollView,
Image,
} from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
left: 20,
};
}
moveRight = () => {
this.setState({left: this.state.left + 10}); // 10 is value of change.
};
moveLeft = () => {
this.setState({left: this.state.left - 10}); // 10 is value of change.
};
render() {
return (
<View style={styles.container}>
<Image
style={{left: this.state.left, height: 120, width: 120}}
source={require('./assets/box.png')}
/>
<Image
style={{height: 20, width: 180, marginTop: -12, marginLeft: 25}}
source={require('./assets/log.png')}
/>
<Image
style={{height: 20, width: 200, marginTop: 150, marginLeft: 185}}
source={require('./assets/log.png')}
/>
<View style={styles.buttonsContainer}>
<TouchableOpacity onPress={this.moveLeft}>
<Image
style={{height: 60, width: 60}}
source={require('./assets/left-button.png')}
/>
</TouchableOpacity>
<TouchableOpacity onPress={this.moveRight}>
<Image
style={{height: 60, width: 60}}
source={require('./assets/right-button.png')}
/>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
textCenter: {
alignSelf: 'center',
textAlign: 'center',
},
levelHeading: {
fontWeight: 'bold',
fontSize: 35,
color: '#CC8A4F',
},
buttonsContainer: {
flexDirection: 'row',
justifyContent: 'space-between',
marginTop: 200,
paddingLeft: 80,
paddingRight: 80,
},
});
Please help me!
Thanks!
import React, { useEffect } from "react";
import { Animated, Text, View, StyleSheet, Button } from "react-native";
const App = () => {
const moveAnimation = new Animated.ValueXY({ x: 10, y: 450 });
useEffect(() => {
moveAnimation;
}, []);
const _moveBallLeft = () => {
Animated.spring(moveAnimation, {
toValue: { x: 250, y: 450 },
}).start();
};
const _moveBallRight = () => {
Animated.spring(moveAnimation, {
toValue: { x: 10, y: 450 },
}).start();
};
return (
<View style={styles.container}>
<Animated.View style={[styles.tennisBall, moveAnimation.getLayout()]}>
<View style={styles.button}>
<Text style={styles.buttonText}>ball</Text>
</View>
</Animated.View>
<View
style={{
flexDirection: "row-reverse",
justifyContent: "space-evenly",
}}
>
<View style={{ alignSelf: "center" }}>
<Button title=">" onPress={_moveBallLeft}></Button>
</View>
<View style={{ alignSelf: "center", marginLeft: "2%" }}>
<Button title="<" onPress={_moveBallRight}></Button>
</View>
</View>
</View>
);
};
export default App;
const styles = StyleSheet.create({
container: {
flex: 2,
backgroundColor: "#ecf0f1",
},
tennisBall: {
display: "flex",
justifyContent: "center",
alignItems: "center",
backgroundColor: "greenyellow",
borderRadius: 100,
width: 100,
height: 100,
},
button: {
paddingTop: 24,
paddingBottom: 24,
},
buttonText: {
fontSize: 24,
color: "#333",
},
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Related
Below you can find the code created so far. You might see that this code works for a simple web program. But when you attempt to see how it is displayed on MOBILE this error code occurs -> (undefined is not an object (evaluating 'p.Picker.Item')
(Device))
Would anyone possibly have an idea of the reason for this error?
I'm new to REACT NATIVE.
import React, { useState } from 'react';
import {
View,
StyleSheet,
Text,
Animated,
Easing,
Pressable,
TextInput,
} from 'react-native';
import { LinearGradient } from 'expo-linear-gradient';
import Constants from 'expo-constants';
import {Card} from 'react-native-paper';
import NumberPlease from 'react-native-number-please';
import { useHeaderHeight } from '#react-navigation/elements';
const OrderPizza = () => {
const initialValues = [{ id: "pizza", value: 3 }];
const [pizzas, setPizzas] = useState(initialValues);
const pizzaNumbers = [{ id: "pizza", label: "🍕", min: 0, max: 99 }];
return (
<View>
<Text>I would like</Text>
<NumberPlease
digits={pizzaNumbers}
values={pizzas}
onChange={(values) => setPizzas(values)}
/>
</View>
);
};
export default function DosingCalculator({ navigation }) {
const headerHeight = useHeaderHeight();
const topMargin = headerHeight + 'px 0 0 0';
const animatedValue = React.useRef(new Animated.Value(0)).current;
const startAnimation = (toValue) => {
Animated.timing(animatedValue, {
toValue,
duration: 400,
easing: Easing.linear,
useNativeDriver: false,
}).start();
};
const left = animatedValue.interpolate({
inputRange: [0, 1],
outputRange: ['2%', '50%'],
extrapolate: 'clamp',
});
const scale = animatedValue.interpolate({
inputRange: [0, 0.5, 1],
outputRange: [1, 0.9, 1],
extrapolate: 'clamp',
});
return (
<LinearGradient colors={['#20c1c1', '#8dc642']} style={styles.gradient}>
<View style={styles.mainContainer}>
<View style={styles.container}>
<Text>
Secondary Readings
<View style={styles.sliderContainer}>
<Animated.View style={[styles.slider, { left }]} />
<Pressable
style={styles.clickableArea}
onPress={startAnimation.bind(null, 0)}>
<Animated.Text
style={[styles.sliderText, { transform: [{ scale }] }]}>
Show
</Animated.Text>
</Pressable>
<Pressable
style={styles.clickableArea}
onPress={startAnimation.bind(null, 1)}>
<Animated.Text
style={[styles.sliderText, { transform: [{ scale }] }]}>
Hide
</Animated.Text>
</Pressable>
</View>
</Text>
<View
style={{
flex: 1,
alignContent: 'center',
justifyContent: 'center',
padding: 12,
}}>
<Text>Pool Volume</Text>
<TextInput
style={{
borderRadius: 10,
padding: 8,
backgroundColor: '#f5f5f5',
}}
onChangeText={(text) => setGallons(text)}
/>
</View>
</View>
<View style={styles.container}>
<Text>Current</Text>
<OrderPizza/>
</View>
<View style={styles.container}>
<Text>Desired</Text>
</View>
</View>
</LinearGradient>
);
}
const styles = StyleSheet.create({
container: {
width: '100%',
alignItems: 'center',
justifyContent: 'center',
textAlign: 'center',
margin: 30,
flexDirection: 'row',
},
gradient: {
flex: 1,
paddingLeft: 15,
paddingRight: 15,
},
sliderContainer: {
width: '75%',
height: 50,
borderRadius: 10,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: '#e0e0e0',
},
mainContainer: {
width: '100%',
margin: 8,
borderRadius: 10,
alignItems: 'center',
backgroundColor: 'white',
},
clickableArea: {
width: '50%',
height: '100%',
justifyContent: 'center',
alignItems: 'center',
},
sliderText: {
fontSize: 17,
fontWeight: '500',
},
slider: {
position: 'absolute',
width: '48%',
height: '90%',
borderRadius: 10,
backgroundColor: '#20c1c1',
},
});
Hello there I am phasing an logic issue where I don't want my other useState render(run) whenever another state change their value because it render full component every time so it initialize default values.
here when useEffect run and it change item value by setitem but after component run again so it initialize default again
import React, { useState, useEffect, useRef, useLayoutEffect } from "react";
import {
Image,
StyleSheet,
TouchableOpacity,
Text,
View,
SafeAreaView,
FlatList,
TextInput,
} from "react-native";
import { EvilIcons } from "#expo/vector-icons";
import { MaterialCommunityIcons, Ionicons } from "#expo/vector-icons";
import axios from "axios";
import { AsyncStorage } from "react-native";
import url from "../url";
const Handlenewspost = ({ navigation }) => {
var items = navigation.getParam("item");
var user = navigation.getParam("user");
var functionforoffset = navigation.getParam("functionforoffset");
const [item, setitem] = useState(items);
var like = item.like;
var found = like.find((element) => {
if (element.username === user.username) return true;
});
found ? (item.userlike = true) : false;
var checklike = "";
item.userlike ? (checklike = "heart") : (checklike = "heart-outline");
item.userlike ? (checkcolor = "red") : (checkcolor = "black");
const [likebutton, setlikebutton] = useState(checklike);
const [postlikes, setpostlikes] = useState(item.likes);
const [likebuttoncolor, setlikebuttoncolor] = useState(checkcolor);
useEffect(() => {
axios
.get(url + "post/byid/" + items._id)
.then((response) => {
setitem(response.data);
})
.catch((err) => {
console.log(err);
console.log(err.response.data.error);
Alert.alert("Something went wrong", err.response.data.error, [
{ text: "OK", onPress: () => console.log("OK Pressed") },
]);
});
}, []);
const onpresshandle = async (item) => {
userToken = await AsyncStorage.getItem("userToken");
id = item._id;
token = userToken;
functionforoffset();
axios
.post(url + "post/like", { token, id })
.then((response) => {
if (!response.data) {
} else {
}
})
.catch((err) => {
console.log(err);
console.log(err.response.data.error);
Alert.alert("Something went wrong", err.response.data.error, [
{ text: "OK", onPress: () => console.log("OK Pressed") },
]);
});
};
function checkcaption(caption) {
if (caption != "") {
return (
<SafeAreaView style={styles.safe}>
<View
style={[
styles.root,
{ flexDirection: "row", alignItems: "center" },
]}
>
<Text style={[styles.textStyle, { fontSize: 15, marginLeft: 0 }]}>
{item.caption}
</Text>
</View>
</SafeAreaView>
);
} else {
return <View></View>;
}
}
return (
<>
<SafeAreaView style={{ flex: 1 }}>
<View style={styles.container}>
<View style={styles.card}>
<View style={styles.cardheader}>
{item.profileimage ? (
<Image
source={{ uri: url + "filename/" + item.profileimage }}
style={{
marginLeft: 16,
marginRight: 8,
height: 40,
width: 40,
borderRadius: 100,
}}
></Image>
) : (
<Image
source={require("../../assets/localbazilogo2.jpeg")}
style={[
styles.profileimage,
{ marginLeft: 16, marginRight: 5 },
]}
></Image>
)}
<Text style={{ fontWeight: "bold", fontSize: 15, marginLeft: 5 }}>
{item.username}
</Text>
</View>
<View style={styles.cardbody}>
{item.filename ? (
<Image
style={styles.cardbodyimage}
resizeMode="stretch"
source={{ uri: url + "filename/" + item.filename }}
></Image>
) : (
<View></View>
)}
</View>
<View style={styles.cardfooter}>
<MaterialCommunityIcons
onPress={() => {
if (item.userlike) {
setlikebutton("heart-outline");
setlikebuttoncolor("black");
setpostlikes(postlikes - 1);
} else {
setlikebutton("heart");
setlikebuttoncolor("red");
setpostlikes(postlikes + 1);
}
item.userlike = !item.userlike;
onpresshandle(item);
}}
name={likebutton}
size={28}
color={likebuttoncolor}
style={{ marginLeft: 10, marginTop: 4 }}
>
{" "}
</MaterialCommunityIcons>
<Text style={{ fontSize: 18, marginLeft: 1 }}>{postlikes}</Text>
<EvilIcons
name="comment"
size={30}
style={{ marginLeft: 20, marginTop: 4 }}
color="black"
/>
<Image
style={{ marginLeft: 20, marginTop: 4 }}
source={require("../../assets/share.png")}
></Image>
</View>
{checkcaption(item.caption)}
<View style={styles.showcomment}>
<Text>
View all {item.comments ? item.comments.length : 0} comments
</Text>
</View>
<View style={styles.comment}>
<View>
{user.profileimage ? (
<Image
source={{ uri: url + "filename/" + user.profileimage }}
style={{
height: 35,
width: 35,
borderRadius: 100,
marginLeft: 14,
}}
></Image>
) : (
<View></View>
)}
</View>
<View style={styles.addcomment}>
<Text
style={{
marginHorizontal: 5,
fontSize: 14,
color: "#9CA3AF",
width: 240,
}}
>
Add Comment
</Text>
</View>
</View>
</View>
</View>
</SafeAreaView>
</>
);
};
export default Handlenewspost;
const styles = StyleSheet.create({
showcomment: { marginLeft: 20, marginBottom: 5 },
addcomment: {
overflow: "hidden",
marginLeft: 20,
marginRight: 20,
padding: 7,
backgroundColor: "#E6E7E9",
borderRadius: 25,
},
comment: {
marginTop: 10,
flexDirection: "row",
alignItems: "center",
},
email: {
flexDirection: "row",
overflow: "hidden",
marginLeft: 20,
marginRight: 20,
marginTop: 10,
marginBottom: 20,
padding: 7,
backgroundColor: "#E6E7E9",
borderRadius: 25,
},
iconout: { width: "20%", alignItems: "center" },
icon: { height: 35, width: 35, resizeMode: "stretch" },
icons: {
flexDirection: "row",
flexWrap: "wrap",
marginTop: 1,
marginHorizontal: 28,
marginBottom: 20,
},
profileimage: {
width: "12%",
height: "170%",
borderRadius: 100,
resizeMode: "stretch",
},
safe: {
flex: 1,
marginTop: -10,
},
root: {
flex: 1,
padding: 16,
},
textStyle: {
fontSize: 14,
},
container: {
justifyContent: "center",
flex: 1,
},
cardfooter: {
flexDirection: "row",
alignItems: "center",
},
cardbodyimage: {
height: 350,
width: "100%",
marginTop: 3,
borderRadius: 3,
},
cardbody: {},
cardheader: {
flexDirection: "row",
alignItems: "center",
marginVertical: 12,
},
card: {
marginVertical: 10,
marginHorizontal: 4,
},
});
I was working on my app with two screens a Main Screen and a Details Screen everything was working, but the code was long, so I tried to split everything into reusable components which caused a
navigation.navigates type error for some reason.
I checked the code multiple times everything makes perfect sense to me is there something am missing here, how do I fixed this error?
Am using react navigation version 5 for the first time.
Here is a sample of the code used:
MainScreen.js
import React from "react";
import { StyleSheet, Text, View, Image, FlatList } from "react-native";
import ArticleList from "../components/ArticleList";
function MainScreen() {
return (
<View style={{ flex: 1 }}>
{/* show the data in a flatlist */}
<ArticleList />
</View>
);
}
MainScreen.navigationOptions = () => {
return {
headerShown: false,
};
};
export default MainScreen;
DetailScreen.js
import React from "react";
import { StyleSheet, Text, View, Dimensions, Image } from "react-native";
import { Feather } from "#expo/vector-icons";
import { SharedElement } from "react-native-shared-element";
import { TouchableOpacity, ScrollView } from "react-native-gesture-handler";
const DetailScreen = (props) => {
const { width, height } = Dimensions.get("window");
const { data } = props.route.params;
return (
<View style={styles.container}>
<View>
<SharedElement id={`item.${data.id}.photo`}>
<Image
resizeMode="cover"
source={{ uri: data.image }}
style={{
width: 400,
height: 300,
borderBottomLeftRadius: 10,
borderBottomRightRadius: 10,
}}
/>
</SharedElement>
<View
style={{
flexDirection: "row",
alignItems: "center",
position: "absolute",
bottom: 14,
left: 10,
}}
>
<SharedElement id={`item.${data.id}.profilePic`}>
<Image
resizeMode="cover"
source={{ uri: data.profilePic }}
style={{
width: 60,
height: 60,
borderRadius: 10,
marginRight: 14,
}}
/>
</SharedElement>
<View
style={{
flex: 1,
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
}}
>
<View>
<SharedElement id={`item.${data.id}.username`}>
<Text
style={{ color: "white", fontSize: 16, fontWeight: "bold" }}
>
{data.username}
</Text>
</SharedElement>
<SharedElement id={`item.${data.id}.readtime`}>
<Text style={{ color: "white", fontSize: 14 }}>
{data.readtime}
</Text>
</SharedElement>
</View>
<TouchableOpacity>
<Feather name="bookmark" size={30} color="white" />
</TouchableOpacity>
</View>
</View>
</View>
<ScrollView style={{ paddingHorizontal: 10, paddingTop: 14 }}>
<SharedElement
id={`item.${data.id}.text`}
style={{ width: width - 30, marginBottom: 14 }}
>
<Text style={{ fontSize: 22, fontWeight: "bold", lineHeight: 32 }}>
{data.title}
</Text>
</SharedElement>
<Text
style={{
fontSize: 14,
lineHeight: 28,
textAlign: "justify",
opacity: 0.5,
}}
>
Paragraph 1
</Text>
<Text
style={{
fontSize: 14,
lineHeight: 28,
textAlign: "justify",
opacity: 0.5,
}}
>
Paragraph 2
</Text>
<View
style={{
marginVertical: 25,
paddingBottom: 20,
flex: 1,
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
}}
>
<TouchableOpacity
style={{ flexDirection: "row", padding: 12, alignItems: "center" }}
>
<Feather name="heart" size={16} color="orange" />
<Text style={{ marginHorizontal: 10 }}>3.4k Likes</Text>
</TouchableOpacity>
</View>
</ScrollView>
<View style={{ position: "absolute", top: 40, left: 10 }}>
<TouchableOpacity onPress={() => props.navigation.goBack()}>
<Feather name="arrow-left" size={24} color="white" />
</TouchableOpacity>
</View>
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
export default DetailScreen;
ArticleList.js
import React from "react";
import {
View,
Text,
StyleSheet,
Image,
Dimensions,
FlatList,
} from "react-native";
import { SharedElement } from "react-native-shared-element";
import TouchableScale from "react-native-touchable-scale";
import { data } from "../data";
function ArticleList({ navigation }) {
const { width, height } = Dimensions.get("window");
return (
<View>
<FlatList
horizontal
showsHorizontalScrollIndicator={false}
style={{ paddingHorizontal: 30 }}
data={data}
keyExtractor={(item) => item.id}
renderItem={({ item }) => {
return (
<View>
<View>
<TouchableScale
activeScale={0.9}
tension={50}
friction={7}
useNativeDriver
onPress={() =>
navigation.navigate("DetailScreen", { data: item })
}
>
{/* to show the horizental news list*/}
<SharedElement id={`item.${item.id}.photo`}>
<Image
source={{ uri: item.image }}
style={{
width: width - 100,
height: height - 350,
borderRadius: 14,
marginRight: 30,
}}
/>
</SharedElement>
{/* to show the news titles inside the pictures*/}
<SharedElement
id={`item.${item.id}.text`}
style={{
width: width - 100,
position: "absolute",
bottom: 90,
left: 10,
paddingHorizontal: 10,
}}
>
<Text style={styles.blogTitle}>{item.title}</Text>
</SharedElement>
{/* to show the pictre of the author of the news article*/}
<View
style={{
flexDirection: "row",
alignItems: "center",
position: "absolute",
bottom: 20,
left: 20,
}}
>
<SharedElement id={`item.${item.id}.profilePic`}>
<Image
resizeMode="cover"
source={{ uri: item.profilePic }}
style={styles.blogProfilePic}
/>
</SharedElement>
</View>
{/* to show the name of the author and read time of article*/}
<View>
<SharedElement id={`item.${item.id}.username`}>
<Text style={styles.blogUsername}>{item.username}</Text>
</SharedElement>
<SharedElement id={`item.${item.id}.readtime`}>
<Text style={styles.readtime}>{item.readtime}</Text>
</SharedElement>
</View>
</TouchableScale>
</View>
</View>
);
}}
/>
</View>
);
}
const styles = StyleSheet.create({
blogTitle: {
color: "white",
fontSize: 24,
fontWeight: "bold",
lineHeight: 28,
},
blogProfilePic: {
height: 50,
width: 50,
borderRadius: 10,
marginRight: 14,
},
blogUsername: {
color: "white",
fontSize: 16,
fontWeight: "bold",
},
readtime: {
fontSize: 14,
color: "white",
},
});
export default ArticleList;
App.js
import React from "react";
import "react-native-gesture-handler";
import { createSharedElementStackNavigator } from "react-navigation-shared-element";
import { NavigationContainer } from "#react-navigation/native";
import MainScreen from "./app/screens/MainScreen";
import DetailScreen from "./app/screens/DetailScreen";
const Stack = createSharedElementStackNavigator();
const App = ({ navigation }) => {
return (
<NavigationContainer>
<Stack.Navigator
initialRouteName="MainScreen"
screenOptions={{ headerShown: false }}
>
<Stack.Screen name="MainScreen" component={MainScreen} />
<Stack.Screen
name="DetailScreen"
component={DetailScreen}
options={(navigation) => ({
headerBackTitleVisible: false,
cardStyleInterpolator: ({ current: { progress } }) => {
return {
cardStyle: {
opacity: progress,
},
};
},
})}
sharedElements={(route) => {
const { data } = route.params;
return [
{
id: `item.${data.id}.photo`,
animation: "move",
resize: "clip",
align: "center-top",
},
{
id: `item.${data.id}.text`,
animation: "fade",
resize: "clip",
align: "left-center",
},
{
id: `item.${data.id}.profilePic`,
animation: "move",
resize: "clip",
align: "left-center",
},
{
id: `item.${data.id}.username`,
animation: "fade",
resize: "clip",
align: "left-center",
},
{
id: `item.${data.id}.readtime`,
animation: "fade",
resize: "clip",
align: "left-center",
},
];
}}
/>
</Stack.Navigator>
</NavigationContainer>
);
};
export default App;
My apologies for the long samples of code I tried to keep everything that is connected directly to the problem.
The problem is the you are accessing navigation outside the navigation stack. When you moved the flatlist to to ArticleList its outside the navigation and it wont get the navigation prop.
You can handle this in two ways.
You can simply pass the navigation from the main screen
function MainScreen({ navigation }) {
return (
{/* show the data in a flatlist */}
< ArticleList navigation={navigation} />
);
}
You can use the useNavigation hook to access navigation outside navigation.
I am using a custom component with image and text. The image is relative to the text. Please see the screenshot.
image 1
image 2.
I have used the TouchableOpacity component as root view for that.
In screenshots when long press on the component, two views are overlapping with shadow. It looks ugly when long press.
Please see the code below for reusable component.
'use strict';
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Image,
} from 'react-native';
export default class ExampleButton extends Component {
constructor (props) {
super (props);
}
_handleOnPress = () => {
console.log('pressed!!!');
};
render () {
console.log (this.props);
return (
<TouchableOpacity
onPress={this.handleOnPress}
>
<View style={styles.btnCompContainer}>
<View
style={{
backgroundColor: '#FFF',
justifyContent: 'center',
borderRadius: 30,
height: 50,
width: '100%',
}}
>
<Text style={styles.btnTxt}>{this.props.buttonText}</Text>
</View>
<View style={[styles.btnElmContainer]}>
<Image
style={[{height: 30, width: 30,resizeMode:'stretch'}]}
source={this.props.image}
/>
</View>
</View>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create ({
btnCompContainer: {
flexDirection: 'row',
alignItems: 'center',
height: 60,
marginLeft: 10,
marginRight: 20,
},
btnElmContainer: {
position: 'absolute',
justifyContent: 'center',
alignItems: 'center',
width: 60,
height: 60,
backgroundColor:'#fff',
borderRadius: 30,
shadowColor: '#000000',
shadowOffset: {
width: 1,
height: 1,
},
elevation:5,
shadowRadius: 2,
shadowOpacity: 0.3,
},
btnTxt: {
marginLeft: 80,
color: '#9e9e9e',
fontSize: 16,
fontWeight: 'bold',
textAlign: 'left',
},
});
Here I am using this reusable component in code.
'use strict';
import React, {Component} from 'react';
import {
Animated,
StyleSheet,
Text,
TextInput,
View,
Image,
ImageBackground,
TouchableOpacity,
Button,
StatusBar,
Easing
} from 'react-native';
// Custom Components
const searchBGImg = require('../assets/search-bg-kit.png');
const houseLogo = require('../Resources/house.png');
import ExampleButton from './components/common/example-button';
export default class TypeSelect extends Component<Props> {
// Navigation Option
static navigationOptions = {
header: null
}
constructor() {
super();
this.state = {
visible: false,
x: new Animated.Value(-100),
};
}
slide = () => {
Animated.spring(this.state.x, {
toValue: 0,
easing: Easing.easeOutBack
}).start();
this.setState({
visible: true,
});
};
gotoSearch = () =>{
this.props.navigation.navigate('DocSearch')
}
componentDidMount(){
this.slide();
}
render() {
return (
<View style={styles.container}>
<ImageBackground source={searchBGImg} style={styles.imgBG}>
<View style={{alignItems:'center', marginBottom:20}}>
<Image style={{height:57, width:69, marginBottom:12}} source={houseLogo} />
</View>
<View>
<Animated.View
style={[styles.slideView, {
transform: [
{
translateX: this.state.x
}
]
}]}>
<ExampleButton image={houseLogo} buttonText={'Click here'} />
<ExampleButton image={houseLogo} buttonText={'Click here'} />
</Animated.View>
</View>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
imgBG:{
flex: 1,
flexDirection: "column",
justifyContent:"center",
width: "100%",
height: "100%"
}
})
It is working fine in iOS, but it's not working in android up to the mark. Please help me to work it in android.
Thanks in advance.
You should use renderToHardwareTextureAndroid prop on <View /> component.
In your example like this:
<View style={styles.btnCompContainer} renderToHardwareTextureAndroid >
<View
style={{
backgroundColor: '#FFF',
justifyContent: 'center',
borderRadius: 30,
height: 50,
width: '100%',
}}
>
<Text style={styles.btnTxt}>{this.props.buttonText}</Text>
</View>
<View style={[styles.btnElmContainer]}>
<Image
style={[{height: 30, width: 30,resizeMode:'stretch'}]}
source={this.props.image}
/>
</View>
</View>
I have two components with realm database one is for listing and other is for adding data. But my problem is that i can't update list when data is adding into second component. I have tried App state listener also but it's not triggering when user come at first screen.
This is list component
import React, { Component } from "react";
import AppScreen from "../AppScreen.js";
import realm from "../databases/RealmController.js";
import colors from "../Ui/colors.js";
import Swipeout from "react-native-swipeout";
import { Icon } from "react-native-vector-icons";
import { NavigationActions } from "react-navigation";
import Dash from "react-native-dash";
import AppStateListener from "react-native-appstate-listener";
import {
AppState,
AppRegistry,
StyleSheet,
Text,
Image,
Button,
View,
FlatList,
TouchableHighlight,
TouchableOpacity,
Alert,
StatusBar,
TextInput
} from "react-native";
type Props = {};
export default class ReminderList extends Component<Props> {
state = {
data: [],
loading: true,
refresh: false,
appState: AppState.currentState
};
static navigationOptions = {
header: null,
title: " List"
};
handleActive() {
console.warn("The application is now active!");
}
handleBackground() {
console.warn("The application is now in the background!");
}
handleInactive() {
console.warn("The application is now inactive!");
}
componentDidMount() {
//this.fetchData();
AppState.addEventListener("change", this.handleAppStateChange);
}
componentWillUnmount() {
AppState.removeEventListener("change", this.handleAppStateChange);
}
gotoAddReminder = () => {
// handle navigation
this.props.screenProps.rootNavigation.navigate("addReminder");
};
handleAppStateChange = nextAppState => {
if (nextAppState === "active") {
this.setState({ data: null });
this.fetchData();
this.setState({ refresh: true });
// console.warn("hello i active");
//this.flatList.scrollToIndex({ animated: true, index: 0 });
}
else {
this.setState({ refresh: false });
// console.warn("hello i inactive");
}
this.setState({ appState: nextAppState });
};
fetchData() {
let reminderList = realm.objects("Reminder");
this.setState({ data: reminderList });
}
renderClientRow(item) {
return (
<TouchableHighlight underlayColor="rgba(192,192,192,1,0.6)">
<View style={styles.cardView}>
<View style={styles.dateView}>
<Text style={styles.dateText}>18</Text>
<Text style={styles.monthText}>Jan</Text>
</View>
<View
style={{
width: 1,
backgroundColor: colors.darkGray,
marginLeft: 15,
marginRight: 20
}}
/>
<View style={{ flexDirection: "row", marginTop: 15, width: "100%" }}>
<View style={{ flexDirection: "column" }}>
<Text style={styles.titleText}>{item.name}</Text>
<Text style={(styles.item, { marginTop: 5 })}>location</Text>
<Dash
style={{
width: 300,
marginTop: 10,
height: 1,
marginRight: 15
}}
/>
<View
style={{
flex: 1,
flexDirection: "row",
marginTop: 5,
marginBottom: 15
}}
>
<Image
style={{
width: 15,
height: 15,
marginTop: 5,
marginRight: 10
}}
source={require("../Image/ic_date.png")}
/>
<Text style={styles.item}>0.40 pm</Text>
</View>
</View>
</View>
</View>
</TouchableHighlight>
);
}
render() {
return (
<View style={styles.container}>
<AppStateListener
onActive={this.handleActive}
onBackground={this.handleBackground}
onInactive={this.handleInactive}
/>
<FlatList
ref={(c) => { this.flatList = c }}
data={this.state.data}
extraData={this.state.refresh}
renderItem={({ item }) => this.renderClientRow(item)}
keyExtractor={item => item.id}
/>
<TouchableOpacity
activeOpacity={0.5}
onPress={() => {
this.gotoAddReminder();
}}
style={styles.TouchableOpacityStyle}
>
<Image
source={{
uri:
"https://reactnativecode.com/wp-content/uploads/2017/11/Floating_Button.png"
}}
style={styles.FloatingButtonStyle}
/>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 0
},
MainContainer: {
justifyContent: "center",
flex: 1,
margin: 10
},
TouchableOpacityStyle: {
position: "absolute",
width: 50,
height: 50,
alignItems: "center",
justifyContent: "center",
right: 30,
bottom: 30
},
FloatingButtonStyle: {
resizeMode: "contain",
width: 50,
height: 50
},
cardView: {
backgroundColor: "#fff",
borderWidth: 0.5,
paddingLeft: 15,
paddingRight: 10,
marginLeft: 10,
marginTop: 10,
marginRight: 10,
borderRadius: 5,
flexDirection: "row"
},
item: {
fontSize: 16,
color: colors.darkGray
},
itemRight: {
fontSize: 18,
textAlign: "right"
},
titleText: {
fontSize: 20,
color: "black",
fontWeight: "400"
},
dateText: {
fontSize: 32,
color: colors.appColor,
fontWeight: "500"
},
monthText: {
fontSize: 22,
color: colors.appColor,
fontWeight: "500"
},
dateView: {
alignItems: "center",
justifyContent: "center",
flexDirection: "column",
marginLeft: 15,
marginRight: 15,
marginTop: 15,
marginBottom: 15
},
rightText: {
fontSize: 22,
color: "black",
textAlign: "right",
fontWeight: "bold"
},
myStarStyle: {
color: "yellow",
backgroundColor: "transparent",
textShadowColor: "black",
textShadowOffset: { width: 1, height: 1 },
textShadowRadius: 2
},
myEmptyStarStyle: {
color: "white"
}
});
This is AddData component
import React, { Component } from "react";
import realm from "../databases/RealmController.js";
import styles from "../Ui/AddClientStyles.js";
import { TextInputLayout } from "rn-textinputlayout";
import DatePicker from "react-native-datepicker";
import {
AppRegistry,
StyleSheet,
Text,
TouchableHighlight,
Button,
View,
ScrollView,
Image,
Alert,
StatusBar,
TextInput
} from "react-native";
const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
type Props = {};
export default class AddReminder extends Component<Props> {
state = {
to: "",
from: "",
name: "",
note: "",
location: ""
};
handlePress = async () => {
var Id = realm.objects("Reminder").length + 1;
realm.write(() => {
realm.create("Reminder", {
id: Id,
name: this.state.name,
note: this.state.note,
location: this.state.location,
to: this.state.to,
from: this.state.from
});
});
this.props.navigation.goBack();
};
render() {
return (
<ScrollView style={styles.container}>
<View style={styles.container}>
<View style={styles.profileContainer} />
<View style={styles.bottomContainer}>
<Text style={[styles.titleText, styles.titleStyle]}>
Basic Information
</Text>
<TextInputLayout style={{ marginTop: 0 }}>
<TextInput
style={styles.textInput}
placeholder={"Reminder Title"}
onChangeText={text => this.setState({ name: text })}
/>
</TextInputLayout>
<TextInputLayout style={styles.inputLayout}>
<TextInput
style={styles.textInput}
placeholder={"Note"}
onChangeText={text => this.setState({ note: text })}
/>
</TextInputLayout>
<TextInputLayout style={styles.inputLayout}>
<TextInput
style={styles.textInput}
placeholder={"Location"}
onChangeText={text => this.setState({ location: text })}
/>
</TextInputLayout>
<Text style={[styles.titleText, styles.titleStyle]}>
Date & Time
</Text>
<View style={styles.dateToContainer}>
<View style={{ flexDirection: "column", width: "30%" }}>
<Text style={styles.textInput}>From</Text>
</View>
<View styles={{ flexDirection: "column", width: "70%" }}>
<DatePicker
style={{ width: 200 }}
date={this.state.from}
mode="datetime"
format="YYYY-MM-DD HH:mm"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
customStyles={{
dateIcon: {
position: "absolute",
left: 0,
top: 4,
marginLeft: 0
},
dateInput: {
marginLeft: 36
}
}}
minuteInterval={10}
onDateChange={datetime => {
this.setState({ from: datetime });
}}
/>
</View>
</View>
<View style={styles.dateContainer}>
<View style={{ flexDirection: "column", width: "30%" }}>
<Text style={styles.textInput}>To</Text>
</View>
<View styles={{ flexDirection: "column", width: "70%" }}>
<DatePicker
style={{ width: 200 }}
date={this.state.to}
mode="datetime"
format="YYYY-MM-DD HH:mm"
confirmBtnText="Confirm"
cancelBtnText="Cancel"
customStyles={{
dateIcon: {
position: "absolute",
left: 0,
top: 4,
marginLeft: 0
},
dateInput: {
marginLeft: 36
}
}}
minuteInterval={10}
onDateChange={datetime => {
this.setState({ to: datetime });
}}
/>
</View>
</View>
<TouchableHighlight
style={styles.btnStyle}
onPress={() => {
this.handlePress();
}}
underlayColor="#fff"
>
<Text style={styles.btnText}>Add Reminder</Text>
</TouchableHighlight>
<TouchableHighlight
style={{marginTop:20}}>
<Text/>
</TouchableHighlight>
</View>
</View>
</ScrollView>
);
}
}
When u use this.props.navigation.goBack(); those components not render again or not call any method that component so can use this.props.navigation.navigate('your_route_path');