I am trying to create an app that changes to one of many images when the image is clicked. I have used touchable opacity and can make the image show an alert when clicked. I just can't get it to change to one of the many others in the file.
Here is all my code so far:
import React from 'react';
import { Component, Stylesheet, useState, TouchableOpacity, Button, View, Text, Image, ScrollView, TextInput, Alert } from 'react-native';
// main part of the app
const App = () => {
var array = [require("./cards/card.png"), require("./cards/card2.png")]
var x = 0
//onclick function
const handlePress = () => {
//some logic
alert("help")
x+=1
}
// what shows up on the app
return (
<ScrollView>
<View>
<Text>{array[x]}</Text>
<Text>{x}</Text>
<View style={{ flexDirection: 'row', justifyContent: 'center' }}>
<TouchableOpacity
onPress={(handlePress)}
>
<Image
style={{
width: 300,
height: 300,
}}
resizeMode="contain"
source={
array[x]
}
/>
</TouchableOpacity>
</View>
</View>
</ScrollView>
);
}
export default App;
The other images that I want the card to change to are in the cards folder. What do I do to make it dynamic and change it to any of the other cards in the folder?
in order to change image or any information in a screen that have been mounted, React have to re-render the screen and put the right information that you want.
To achieve this, you should use React states https://reactnative.dev/docs/state
Your code could be like this:
import React from 'react';
import { Component, Stylesheet, useState, TouchableOpacity, Button, View, Text, Image, ScrollView, TextInput, Alert } from 'react-native';
// main part of the app
const App = () => {
const [card, setCard] = useState(0); //initial state
var array = [
"./cards/card.png",
"./cards/card2.png"
]
//onclick function
const handlePress = () => {
//some logic
//set card state to the next index
setCard( current => current + 1);
//so everytime you click function the state will change and this re-render your component with the new data.
}
// what shows up on the app
return (
<ScrollView>
<View>
<Text>{array[card]}</Text>
<View style={{ flexDirection: 'row', justifyContent: 'center' }}>
<TouchableOpacity
onPress={(handlePress)}
>
<Image
style={{
width: 300,
height: 300,
}}
resizeMode="contain"
source={ require(array[card]) }
/>
</TouchableOpacity>
</View>
</View>
</ScrollView>
);
}
export default App;
Related
I have created a functionality , In which show the Progress bar and it's value change according to scrolling the view. the progress bar value should depend that scrolling is end or not if the scrolling is end then the progress bar should completely filled.
I have tired but it's not working. Here my code:
import React, {useState, useEffect} from 'react';
import * as Progress from 'react-native-progress';
import { Card } from 'react-native-paper';
import { Text, View, StyleSheet,ScrollView } from 'react-native';
const scrollView_height = 0;
const scrollViewContent_height = 0;
export default function App() {
const UpdateProgressBar = (progress) => {
setProgress(
Math.abs(
progress.nativeEvent.contentOffset.y /
(scrollViewContent_height - scrollView_height),
),
);
};
return (
<View style={styles.container}>
<Progress.Bar
style={{
position: 'relative',
bottom: 6,
borderTopLeftRadius: 40,
borderTopRightRadius: 40,
}}
height={3}
borderWidth={0}
progress={progress_count}
color="red"
width={widthToDp('82%')}
/>
<ScrollView
showsVerticalScrollIndicator={false}
bounces={false}
contentContainerStyle={{paddingBottom: 0}}
onContentSizeChange={(width, height) => {
scrollViewContent_height = height;
}}
onScroll={UpdateProgressBar}
onLayout={(event) =>
(scrollView_height = event.nativeEvent.layout.height)
}
scrollEventThrottle={12}>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a
shareable url.
</Text>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a
shareable url.
</Text>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a
shareable url.
</Text>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a
shareable url.
</Text>
<Card>
<AssetExample />
</Card>
</ScrollView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
}
});
Please Suggest the Solution.
import React, {useState, useEffect} from 'react';
import * as Progress from 'react-native-progress';
import { Card } from 'react-native-paper';
import { Text, View, StyleSheet,ScrollView } from 'react-native';
export default function App() {
const [scrollView_height, setScrollView_height] = useState(0)
const [scrollViewContent_height, setScrollViewContent_height] = useState(0)
const [progress, setProgress] = useState(0)
const UpdateProgressBar = (value) => {
setProgress(
Math.abs(
value.nativeEvent.contentOffset.y /
(scrollViewContent_height - scrollView_height),
),
);
};
return (
<View style={styles.container}>
<Progress.Bar
style={{
position: 'relative',
bottom: 6,
borderTopLeftRadius: 40,
borderTopRightRadius: 40,
}}
height={3}
borderWidth={0}
progress={progress}
color="red"
width={widthToDp('82%')}
/>
<ScrollView
showsVerticalScrollIndicator={false}
bounces={false}
contentContainerStyle={{paddingBottom: 0}}
onContentSizeChange={(width, height) => {
setScrollView_height(height);
}}
onScroll={UpdateProgressBar}
onLayout={(event) =>
setScrollView_height(event.nativeEvent.layout.height)
}
scrollEventThrottle={12}>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a
shareable url.
</Text>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a
shareable url.
</Text>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a
shareable url.
</Text>
<Text style={styles.paragraph}>
Change code in the editor and watch it change on your phone! Save to get a
shareable url.
</Text>
<Card>
<AssetExample />
</Card>
</ScrollView>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
}
});
I have a url in the Webview like https://www.nytimes.com/ The current code works inital page load but If I type tap anything in the link, the page takes a while to load and there are no loading indicators in the website. Is there any way we can put a page loading indicator in React Native while we click on any link or page loading specially if it is server side rendered like next js?
Here is my ReactNative code.
import * as React from 'react';
import {
View,
Text,
Image,
SafeAreaView,
ScrollView,
TextInput,
TouchableOpacity,
} from 'react-native';
import styles from './styles';
import { WebView } from 'react-native-webview';
// import WelcomeSwiper from '../../components/WelcomeScreen/WelcomeSwiper';
import LoadingIcon from '../../components/Loading/index.js';
const WebView = ({ navigation }) => {
return (
<SafeAreaView style={styles.container}>
<WebView
javaScriptEnabled={true}
domStorageEnabled={true}
renderLoading={LoadingIcon}
source={{ uri: 'https://www.nytimes.com/ ' }}
startInLoadingState={true}
/>
</SafeAreaView>
);
};
export default WebView;
Here is my loading component
import React from 'react';
import { StyleSheet, Platform, ActivityIndicator } from 'react-native';
const LoadingIcon = () => {
return (
<ActivityIndicator
color='#009688'
size='large'
style={styles.ActivityIndicatorStyle}
/>
);
}
export default LoadingIcon;
const styles = StyleSheet.create(
{
WebViewStyle:
{
justifyContent: 'center',
alignItems: 'center',
flex: 1,
marginTop: (Platform.OS) === 'ios' ? 20 : 0
},
ActivityIndicatorStyle: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
}
});
we can use these two approaches to get the result:
You can check if the WebView is loading something or not with the onLoadProgress method. This method gives you a number between 0 and 1. If the page is fully loaded it will return number 1, update your state and show the ActivityIndicator according to it:
you can use onLoadStart and onLoadEnd to update your state and show the ActivityIndicator according to it!
for more info check the: https://github.com/react-native-community/react-native-webview/blob/master/docs/Reference.md#onloadprogress
you can also use your ActivityIndicator wrapped by WebView, *do not Forget this method works in ios for android put it outside of WebView
and this is a working code sample for you:
import React, {useState} from 'react';
import {View, Text, SafeAreaView, ActivityIndicator} from 'react-native';
import {WebView} from 'react-native-webview';
function WebViewTest() {
const [isLoading, setLoading] = useState(false);
return (
<SafeAreaView style={{flex: 1}}>
<WebView
source={{uri: 'https://www.nytimes.com/'}}
onLoadStart={(syntheticEvent) => {
setLoading(true);
}}
onLoadEnd={(syntheticEvent) => {
setLoading(false);
}} />
{isLoading && (
<View style={{flex: 10, backgroundColor: 'white'}}>
<ActivityIndicator
color="#009688"
size="large"
// style={{position: 'absolute', left: 200, top: 300}}
/>
</View>
)}
</SafeAreaView>
);
}
export default WebViewTest;
I hope it helps
I use onLoadProgress to solve this issue.
renderLoading function is just called at the initial loading state of webview component. Using renderLoading is not helpful to show activity indicators at any tap on page links or navigating between webview pages.
Checking onLoadStart and onLoadEnd is useful in android but in iOS onLoadEnd is not called in the back navigation gesture which results in endless spinning of activity indicator.
onLoadProgress returns a number between 0-1 while webview is in the loading state. You check its progress state and update your activity indicator state.
For more information about onLoadProgress: onLoadProgress
Here is a working code example for you:
import React, {useState} from 'react';
import {View, Text, SafeAreaView, ActivityIndicator} from 'react-native';
import {WebView} from 'react-native-webview';
function WebViewTest() {
const [isLoading, setLoading] = useState(false);
return (
<SafeAreaView style={{flex: 1}}>
<WebView
source={{uri: 'https://www.nytimes.com/'}}
onLoadProgress={({nativeEvent}) => {
if (nativeEvent.progress != 1 && isLoading == false ) {
setLoading(true)
} else if (nativeEvent.progress == 1 ) {
setLoading(false)
}
}}
/>
{isLoading && (
<View style={{flex: 10, backgroundColor: 'white'}}>
<ActivityIndicator
color="#009688"
size="large"
// style={{position: 'absolute', left: 200, top: 300}}
/>
</View>
)}
</SafeAreaView>
);
}
export default WebViewTest;
I want to play only a segment of the animation in react native using lottie view
the length is about 5 seconds while in speed={1} I wanna play only the first 3 seconds and then go to the next screen
the code is down below
LogoScreen.js :
import React from 'react';
import { StyleSheet, View, Image, TextInput, StatusBar, Text } from "react-native";
import Icons from 'react-native-vector-icons/Ionicons';
import LottieView from "lottie-react-native";
export default class ChatScreen extends React.Component {
onAnimationFinish = () => {
this.props.navigation.navigate("Login")
}
render () {
return (
<View style={styles.container}>
<StatusBar barStyle="light-content" backgroundColor="#161f3d" />
<View>
<LottieView
source={require('../assets/animations/lottie/MotionCorpse-Jrcanest.json')}
style={{ justifyContent: "center", alignSelf: "center", height: "100%", width: "100%" }}
autoPlay
loop={false}
speed={1}
onAnimationFinish={this.onAnimationFinish}
/>
</View>
</View>
)
}
Well you can do it by several ways, one of the way would be like below.
You can use ref to play it manually and then after 3 seconds just redirect to next screen.
import React from 'react';
import { StyleSheet, View, Image, TextInput, StatusBar, Text } from "react-native";
import Icons from 'react-native-vector-icons/Ionicons';
import LottieView from "lottie-react-native";
export default class ChatScreen extends React.Component {
componentDidMount() {
this.anim.play();
setTimeout(() => {
this.props.navigation.navigate("Login")
}, 3000);
}
render() {
return (
<View style={styles.container}>
<StatusBar barStyle="light-content" backgroundColor="#161f3d" />
<View>
<LottieView
source={require('../assets/animations/lottie/MotionCorpse-Jrcanest.json')}
style={{ justifyContent: "center", alignSelf: "center", height: "100%", width: "100%" }}
autoPlay={false}
loop={false}
speed={1}
ref={animation => { this.anim = animation; }}
/>
</View>
</View>
)
}
}
Another way is if you know exact frame numbers then you can play animation till that frame which completes at 3 seconds. It is already mentioned in Lottie documentation.
this.animation.play(30, 120);
I am new to react native and am trying to make my camera component pop up whenever I click on a button. I am able to get the camera to render in App.js, but the minute I try to get it rendering in the component it just doesn't work. Should I use state to get this to render? If so, why doesn't react native allow you to just render a component within a component? I'm trying to understand the concept of components calling other components. Heres my code:
import React, {Component} from 'react';
import {Button, StyleSheet, Text, View} from 'react-native';
import DeviceCamera from './camera';
class CameraButton extends Component {
render() {
return (
<View style={styles.container}>
<Text> Button to Open Camera </Text>
<Button
onPress={() => {
<DeviceCamera />;
}}
title="click me to open the camera!"
color="#841584"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
export default CameraButton;
I was trying to use the on press function to call the camera component but perhaps I am misunderstanding something.
Yeah, I would probably just use state here
class CameraButton extends Component {
showCamera = () => this.setState({ showCamera: true });
render() {
return (
<View style={styles.container}>
<Text> Button to Open Camera </Text>
<Button
onPress={this.showCamera}
title="click me to open the camera!"
color="#841584"
/>
{this.state.showCamera && <DeviceCamera />}
</View>
);
}
}
With JSX, you can use foo && <Bar />; if foo evaluates to something truthy, then it will render your component, otherwise it will not.
I'm trying to build an app and it was working but for some reason now everytime I try to export something it no longer works (stays greyed out).
I have copy and pasted a page and just change the file name and the export class still stays greyed out.
I have deleted the node folder, cleared the cache, and reinstall the cache. Still won't work
Created a new file in the screen and component folder, copy pasted a working page (screen file to a screen file & component file to component file). The export class still stays greyed out.
example of a button component
import React, { Component } from 'react';
import {View, StyleSheet, Dimensions} from 'react-native';
export default function Timer(props) {
return(
<View style={styles.Button}>
<View>
{ props.children }
</View>
</View>
)
}
const styles = StyleSheet.create({
Button: {
height:31,
width: 87,
borderRadius: 10,
backgroundColor: '#E0F7EF',
display: 'flex',
justifyContent: 'center', /* center items vertically, in this case */
alignItems: 'center', /* center items horizontally, in this case */
},
})
Example of a screen component
import React, {Component} from 'react';
import * as firebase from 'firebase';
import { NavigationActions, StackNavigator } from 'react-navigation';
import{ ImageBackground, Dimensions, View, ScrollView, SafeAreaView, TextInput, Picker } from 'react-native';
import { SimpleLineIcons } from '#expo/vector-icons';
import { Container, Header, Content, Card, CardItem, Body, Text } from 'native-base';
import { MaterialCommunityIcons, FontAwesome, MaterialIcons, Ionicons} from '#expo/vector-icons';
import Strings from '../utils/Strings';
var styles = require('../../assets/files/Styles');
var {height, width} = Dimensions.get('window');
//NAVIGATION AT TOP
export default class Cardio extends Component {
static navigationOptions = {
title: `${Strings.ST201}`,
};
navigateToScreen = (route) => () => {
const navigateAction = NavigationActions.navigate({
routeName: route,
});
this.props.navigation.dispatch(navigateAction);
}
render () {
return (
<Container style={styles.background_general}>
<ScrollView>
<View style={{flexDirection:'column', backgroundColor: '#000000', height: height * 0.25}}>
<ImageBackground
source={require('../../assets/images/header.jpg')}
style={{flex: 1, width: null, height: null}}>
</ImageBackground>
</View>
<View style={styles.cardslayout}>
<TextInput
style={styles.CommentBox}
placeholder = 'sets'
returnKeyType="done"
/>
<TextInput
style={styles.CommentBox}
placeholder = 'Reps'
returnKeyType="done"
/>
</View>
<View>
<TextInput />
</View>
<View style={styles.cardslayout}>
<Content horizontal={true}>
{/*Bike*/}
<Card>
<CardItem style={styles.card}>
<Text>
<MaterialIcons name="directions-bike" size={32} color="white"/>
</Text>
</CardItem>
</Card>
<Card>
<CardItem style={styles.card}>
<Text>
<MaterialCommunityIcons name="run-fast" size={32} color="white"/>
</Text>
</CardItem>
</Card>
<Card>
<CardItem style={styles.card}>
<Text>
<Ionicons name="ios-walk" size={32} color="white"/>
</Text>
</CardItem>
</Card>
</Content>
</View>
{/*END OF CUSTOM INPUT*/}
</ScrollView>
</Container>
)
}
}
This is what I mean by it being grayed out.
This is a custom button file in the component folder.
You can see the export default function working in the custom button file. Now am going to create a test file and copy and paste the same code into it and simply change the function name. Now before I change the function name the "export default function" turns grey but I change the name to reduce confusion here.