WebView does not appear when onPress() triggered - javascript

The code below creates a card, within this card I want to load the url from the card and make a webview appear using the 'react-native-webview' import.
import {View, Linking, TouchableNativeFeedback} from 'react-native';
import {Text, Button, Card, Divider} from 'react-native-elements';
import moment from 'moment';
import {WebView} from 'react-native-webview';
export default class DataItem extends React.Component {
render() {
const {title, description, publishedAt, source, urlToImage, url} =
this.props.article;
const {noteStyle, featuredTitleStyle} = styles;
const time = moment(publishedAt || moment.now()).fromNow();
return (
<TouchableNativeFeedback
useForeground
onPress={() => <WebView source={{uri: url}} style={{marginTop: 20}} />}>
<Card>
<Text style={{fontWeight: 'bold'}}> {title || 'YEET'} </Text>
<Divider style={{backgroundColor: '#dfe6e9', margin: 5}} />
<Card.Image source={{uri: urlToImage}} />
<Text style={{marginBottom: 10}}>{description || 'Read More..'}</Text>
<Divider style={{backgroundColor: '#dfe6e9'}} />
<View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
<Text style={noteStyle}>{source.name.toUpperCase()}</Text>
<Text style={noteStyle}>{time}</Text>
</View>
</Card>
</TouchableNativeFeedback>
);
}
}

I assume you are trying to show a webview when the card press. The problem I see in your code is that you are trying to return a component on Touchable onPress which is not a correct way. You have to keep the state for that like when you press the card state goes active and shows the webview.
Try This
import { View, Linking, TouchableNativeFeedback } from 'react-native';
import { Text, Button, Card, Divider } from 'react-native-elements';
import moment from 'moment';
import { WebView } from 'react-native-webview';
export default class DataItem extends React.Component {
state = {
showWebview: false,
};
render() {
const {
title,
description,
publishedAt,
source,
urlToImage,
url,
} = this.props.article;
const { noteStyle, featuredTitleStyle } = styles;
const time = moment(publishedAt || moment.now()).fromNow();
return (
<View>
<TouchableNativeFeedback
useForeground
onPress={() => {
this.setState({ showWebview: true });
}}
>
<Card>
<Text style={{ fontWeight: 'bold' }}> {title || 'YEET'} </Text>
<Divider style={{ backgroundColor: '#dfe6e9', margin: 5 }} />
<Card.Image source={{ uri: urlToImage }} />
<Text style={{ marginBottom: 10 }}>
{description || 'Read More..'}
</Text>
<Divider style={{ backgroundColor: '#dfe6e9' }} />
<View
style={{ flexDirection: 'row', justifyContent: 'space-between' }}
>
<Text style={noteStyle}>{source.name.toUpperCase()}</Text>
<Text style={noteStyle}>{time}</Text>
</View>
</Card>
</TouchableNativeFeedback>
{this.state.showWebView && ( // it will show webview whew showWebview is true.
<WebView source={{ uri: url }} style={{ marginTop: 20 }} />
)}
</View>
);
}
}

Related

How to choose muliple potions from JSON in React Native?

I have rendered data from an array / JSON and its shows on screen. When I click on an option its heiglights the box on which I have clicked. But I want to heightlight multiple options or want to choose multiple options from array.
I am not getting how to do that. It only shows only one option and when I click click on another otion it heighlights the option but dehighlights the previous option.
Please suggest me solution for that. I have share image and code below -
Image:
enter image description here
Code:
import React, {useContext} from 'react';
import {
Dimensions,
Image,
StatusBar,
Text,
TouchableHighlight,
} from 'react-native';
import {Box, Button, ScrollView} from 'native-base';
import {useState} from 'react';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import {styles} from './createHabitStyles';
import {ApplicationContext} from '../../../context/application_ctx';
import {IconCheck, IconCircleBack} from '../../../svgIcons/icons';
export function ChooseTechnique({navigation, choose}) {
const [chooseButton, setChooseButton] = useState();
const {habitNavigation,setHabitNavigation,chooseSpan} =
useContext(ApplicationContext);
const {techniques, setTechniques} = useContext(ApplicationContext);
let techniqueChooser = [
{button: 'Mood Journal',src:require('../../../assets/images/techniqueBackgrounds/journal.jpg')},
{button: 'Meditation',src:require('../../../assets/images/techniqueBackgrounds/meditation.jpg')},
{button: 'ABCD',src:require('../../../assets/images/techniqueBackgrounds/abcd.jpg')},
{button: 'Optimism',src:require('../../../assets/images/techniqueBackgrounds/optimism1.jpg')},
{button: 'Journal',src:require('../../../assets/images/techniqueBackgrounds/journal.jpg')},
{button: 'Motivation',src:require('../../../assets/images/techniqueBackgrounds/motivation.jpg')},
{button: 'Defusion',src:require('../../../assets/images/techniqueBackgrounds/defusion.jpg')},
{button: 'Values',src:require('../../../assets/images/techniqueBackgrounds/goals.jpg')},
{button: 'Goals',src:require('../../../assets/images/techniqueBackgrounds/values.jpg')},
{button: 'Thought Record',src:require('../../../assets/images/techniqueBackgrounds/thought.jpg')},
{button: 'Breathe',src:require('../../../assets/images/techniqueBackgrounds/breathe.jpg')},
];
return (
<>
<StatusBar
backgroundColor={'#F5F5F5'}
translucent={false}
barStyle={'dark-content'}
/>
<Box style={styles.MainBox}>
<ScrollView>
<Box style={{height: '6%', alignItems: 'center'}}>
<Text style={styles.stepperTxt}>Create Habit</Text>
</Box>
<IconCircleBack
onPress={() => setHabitNavigation(0)}
style={{...styles.iconBack, top: '2.2%'}}
/>
<Box style={styles.choosenBox}>
<Box
style={styles.choosenButton}>
<Text style={{fontSize: 15, color: '#5D535C'}}>
{chooseSpan.but}
</Text>
</Box>
{chooseButton !== undefined ? (
<Box
style={styles.choosenButtonDynamic}>
<Text style={{fontSize: 15, color: '#5D535C'}}>
{techniques}
</Text>
</Box>
) : (
''
)}
</Box>
<Box style={{height: '6%', marginTop: '2%'}}>
<Text style={styles.headTxt}>Choose a technique</Text>
<Text
style={styles.subHeading}>
Create a habit from any one of your susbcribed techniques
</Text>
</Box>
<Box style={{height: 1050}}>
<Box style={{alignItems: 'center'}}>
{techniqueChooser.map((data, i) => {
return (
<TouchableHighlight
key={i}
underlayColor={'none'}
onPress={() => {
setChooseButton(i), setTechniques(data.button);
}}
style={styles.cardTechniques}>
<>
{chooseButton === i ? <IconCheck style={{position:'absolute',right:10,bottom:"10%",zIndex:1}} /> : ""}
<Image
style={styles.imageOptimism}
resizeMethod="scale"
resizeMode="cover"
source={data.src}
/>
<Image
style={{
...styles.imageBackdrop,
display: `${chooseButton === i ? 'none' : 'flex'}`,
}}
resizeMethod="scale"
resizeMode="cover"
source={require('../../../assets/images/techniqueBackgrounds/backdrop.png')}
/>
<Box
style={styles.buttonTechnique}>
<Text
style={{
fontSize: 14,
fontWeight: 'bold',
color: '#5D535C',
}}>
{data.button}
</Text>
</Box>
</>
</TouchableHighlight>
);
})}
</Box>
</Box>
</ScrollView>
<Box
style={{
position: 'absolute',
bottom: '3%',
width: '100%',
alignItems: 'center',
}}>
<Button
isDisabled={chooseButton !== undefined ? false : true}
style={{
...styles.button2,
backgroundColor: `${
chooseButton !== undefined ? '#36A2D0' : '#6D7A82'
}`,
}}
isLoadingText="Continue"
spinnerPlacement="end"
onPress={() =>{techniques === "Meditation" ? setHabitNavigation(4) : techniques === 'Breathe' ? setHabitNavigation(6) : setHabitNavigation(3)}}>
<MaterialIcons
name="arrow-forward-ios"
style={{
fontSize: 20,
color: `${chooseButton !== undefined ? 'white' : 'black'}`,
}}
/>
</Button>
</Box>
</Box>
</>
);
}
Instead of setting individual id to your state, you add your id to an array then set that array to your state.
onPress={() => {
let newArray = [...chooseButton, i];
setChooseButton(newArray),
setTechniques(data.button);
}}
You then use that array to conditionally render your IconCheck by checking if the id exists in the chooseButton array.

how to select multiple elements from an json array

I want to select the elements rendered using json array data,
i am rendering the elements using json array where only most recent clicked element is getting select,i want to select every clicked element,like state of previously clicked element should be saved.
In simple words when the element is clicked first time then it will be selected and when i click next element then the previous clicked element should remain selected.Click here to check image
import React, {useContext} from 'react';
import {
Dimensions,
Image,
StatusBar,
Text,
TouchableHighlight,
} from 'react-native';
import {Box, Button, ScrollView} from 'native-base';
import {useState} from 'react';
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import {styles} from './createHabitStyles';
import {ApplicationContext} from '../../../context/application_ctx';
import {IconCheck, IconCircleBack} from '../../../svgIcons/icons';
export function ChooseTechnique({navigation, choose}) {
const [chooseButton, setChooseButton] = useState();
const {habitNavigation,setHabitNavigation,chooseSpan} =
useContext(ApplicationContext);
const {techniques, setTechniques} = useContext(ApplicationContext);
let techniqueChooser = [
{button: 'Mood Journal',src:require('../../../assets/images/techniqueBackgrounds/journal.jpg')},
{button: 'Meditation',src:require('../../../assets/images/techniqueBackgrounds/meditation.jpg')},
{button: 'ABCD',src:require('../../../assets/images/techniqueBackgrounds/abcd.jpg')},
{button: 'Optimism',src:require('../../../assets/images/techniqueBackgrounds/optimism1.jpg')},
{button: 'Journal',src:require('../../../assets/images/techniqueBackgrounds/journal.jpg')},
{button: 'Motivation',src:require('../../../assets/images/techniqueBackgrounds/motivation.jpg')},
{button: 'Defusion',src:require('../../../assets/images/techniqueBackgrounds/defusion.jpg')},
{button: 'Values',src:require('../../../assets/images/techniqueBackgrounds/goals.jpg')},
{button: 'Goals',src:require('../../../assets/images/techniqueBackgrounds/values.jpg')},
{button: 'Thought Record',src:require('../../../assets/images/techniqueBackgrounds/thought.jpg')},
{button: 'Breathe',src:require('../../../assets/images/techniqueBackgrounds/breathe.jpg')},
];
return (
<>
<StatusBar
backgroundColor={'#F5F5F5'}
translucent={false}
barStyle={'dark-content'}
/>
<Box style={styles.MainBox}>
<ScrollView>
<Box style={{height: '6%', alignItems: 'center'}}>
<Text style={styles.stepperTxt}>Create Habit</Text>
</Box>
<IconCircleBack
onPress={() => setHabitNavigation(0)}
style={{...styles.iconBack, top: '2.2%'}}
/>
<Box style={styles.choosenBox}>
<Box
style={styles.choosenButton}>
<Text style={{fontSize: 15, color: '#5D535C'}}>
{chooseSpan.but}
</Text>
</Box>
{chooseButton !== undefined ? (
<Box
style={styles.choosenButtonDynamic}>
<Text style={{fontSize: 15, color: '#5D535C'}}>
{techniques}
</Text>
</Box>
) : (
''
)}
</Box>
<Box style={{height: '6%', marginTop: '2%'}}>
<Text style={styles.headTxt}>Choose a technique</Text>
<Text
style={styles.subHeading}>
Create a habit from any one of your susbcribed techniques
</Text>
</Box>
<Box style={{height: 1050}}>
<Box style={{alignItems: 'center'}}>
{techniqueChooser.map((data, i) => {
return (
<TouchableHighlight
key={i}
underlayColor={'none'}
onPress={() => {
setChooseButton(i), setTechniques(data.button);
}}
style={styles.cardTechniques}>
<>
{chooseButton === i ? <IconCheck style={{position:'absolute',right:10,bottom:"10%",zIndex:1}} /> : ""}
<Image
style={styles.imageOptimism}
resizeMethod="scale"
resizeMode="cover"
source={data.src}
/>
<Image
style={{
...styles.imageBackdrop,
display: `${chooseButton === i ? 'none' : 'flex'}`,
}}
resizeMethod="scale"
resizeMode="cover"
source={require('../../../assets/images/techniqueBackgrounds/backdrop.png')}
/>
<Box
style={styles.buttonTechnique}>
<Text
style={{
fontSize: 14,
fontWeight: 'bold',
color: '#5D535C',
}}>
{data.button}
</Text>
</Box>
</>
</TouchableHighlight>
);
})}
</Box>
</Box>
</ScrollView>
<Box
style={{
position: 'absolute',
bottom: '3%',
width: '100%',
alignItems: 'center',
}}>
<Button
isDisabled={chooseButton !== undefined ? false : true}
style={{
...styles.button2,
backgroundColor: `${
chooseButton !== undefined ? '#36A2D0' : '#6D7A82'
}`,
}}
isLoadingText="Continue"
spinnerPlacement="end"
onPress={() =>{techniques === "Meditation" ? setHabitNavigation(4) : techniques === 'Breathe' ? setHabitNavigation(6) : setHabitNavigation(3)}}>
<MaterialIcons
name="arrow-forward-ios"
style={{
fontSize: 20,
color: `${chooseButton !== undefined ? 'white' : 'black'}`,
}}
/>
</Button>
</Box>
</Box>
</>
);
}

React Native Draggable Flatlist with Swipeable Item not working

I am new to React native. I am trying draggable Flatlist with Swipeable item which is not working. But when i tried with example it's working but not with real code.
https://snack.expo.dev/#computerjazz/swipeable-draggable-list -- Working
//Here is my first component
This is my first component where i have added only draggable flatlist.But when i tried with example it's working but not with real code.
//Correct Draggable list
import React, {useState} from 'react';
import {StyleSheet, Text, TouchableOpacity, View, CheckBox} from 'react-native';
import DraggableFlatList from 'react-native-draggable-flatlist';
import LABEL from '../common/ContentTranslations';
import RowComponent from './RowComponent';
function DashboardSortableListComponent(props) {
const [data, setData] = useState(props.data);
const disableText = props.appLanguage
? LABEL[props.appLanguage].LABEL_DISABLE
: '';
const data_order = props.data;
const order = Object.keys(data_order);
const renderItem = ({item, index, drag, isActive}) => (
<View style={styles.item}>
<TouchableOpacity onLongPress={drag}>
<RowComponent
key={item.pid}
rowData={item}
index={index}
totalRows={item.length}
navigate={props.navigate}
appLanguage={props.appLanguage}
disableText={disableText}
removeCurrencyPairFromList={props.removeCurrencyPairFromList}
/>
</TouchableOpacity>
</View>
);
return (
<View style={styles.screen}>
<View style={{flex: 1}}>
<DraggableFlatList
data={data}
renderItem={renderItem}
keyExtractor={(item, index) => index.toString()}
onDragEnd={({data}) => setData(data)}
updateOrder={props.onUpdateOrder}
order={order}
disableText={disableText}
navigate={props.navigate}
appLanguage={props.appLanguage}
refreshCurrencyPairsList={props.refreshCurrencyPairsList}
removeCurrencyPairFromList={props.removeCurrencyPairFromList}
/>
</View>
</View>
);
}
const styles = StyleSheet.create({
screen: {
//marginTop: 24,
flex: 1,
//backgroundColor: '#212121',
},
item: {
// flexDirection: 'row',
// justifyContent: 'space-between',
},
});
export default DashboardSortableListComponent;
//Here is my second component where i have added Swipeable list in another component.
import React from 'react';
import Swipeout from 'react-native-swipeout';
import {Text, View, Animated, TouchableOpacity} from 'react-native';
import {TouchableHighlight} from 'react-native-gesture-handler';
import HTMLText from 'react-native-html-to-text';
import {Helper} from '../common/helpers/Helper';
import Icon from 'react-native-vector-icons/Ionicons';
import Swipeable from 'react-native-gesture-handler/Swipeable';
import SwipeableItem, {
useSwipeableItemParams,
} from 'react-native-swipeable-item';
import DraggableFlatList, {
ScaleDecorator,
} from 'react-native-draggable-flatlist';
let createReactClass = require('create-react-class');
let styles = require('../assets/stylesheet/stylesheet');
const RowComponent = createReactClass({
render: function () {
let swipeoutBtns = [
{
text: this.props.disableText,
backgroundColor: '#dfb665', //ff3333
underlayColor: '#555d66',
color: '#000000',
onPress: () => {
this.props.removeCurrencyPairFromList(this.props.rowData);
},
},
,
];
const UnderlayRight = ({removeCurrencyPairFromList}) => (
<Animated.Text
style={{
backgroundColor: '#dfb665',
underlayColor: '#555d66',
color: '#000000',
flex: 1,
}}>
<TouchableOpacity
onPress={() =>
this.props.removeCurrencyPairFromList(this.props.rowData)
}>
<Text>{this.props.disableText}</Text>
</TouchableOpacity>
</Animated.Text>
);
return (
<View
style={
this.props.index === this.props.totalRows - 1
? styles.cpLastRowStyle
: styles.cpNormalRowStyle
}>
<ScaleDecorator>
{/* <SwipeableItem
key={this.props.rowData.pid}
item={this.props.rowData}
overSwipe={50}
//swipeDamping={5}
renderUnderlayRight={() => (
<UnderlayRight
removeCurrencyPairFromList={
this.props.removeCurrencyPairFromList
}
/>
)}
snapPointsRight={[150]}> */}
<Swipeout
left={swipeoutBtns}
style={{backgroundColor: '#414a53'}}
autoClose={true}
buttonWidth={100}
sensitivity={10}>
<View>
{Helper.isChartsAvailable(
this.props.rowData.currencyPair,
this.props.rowData.graphCurrencyPair,
) ? (
<TouchableHighlight
underlayColor={'#000000'}
delayLongPress={50}
style={{backgroundColor: '#333e48'}}
{...this.props.sortHandlers}
onPress={() =>
this.props.navigate('Charts', {
currencyPair: this.props.rowData.graphCurrencyPair,
bid: this.props.rowData.bid,
offer: this.props.rowData.offer,
graphCurrencyPair: this.props.rowData.graphCurrencyPair,
productName: Helper.selectProductNameBaseOnLang(
this.props.appLanguage,
this.props.rowData,
),
})
}>
<View style={[styles.rowstyle]}>
<HTMLText
style={[
styles.width100,
styles.customFont,
styles.textGold,
]}
html={Helper.selectProductNameBaseOnLang(
this.props.appLanguage,
this.props.rowData,
)}
/>
<Text style={[styles.width60, styles.customFont]}>
{Helper.getDecimalPointsForCurrencyPairs(
this.props.rowData.currencyPair,
) != -1
? this.props.rowData.bid.toFixed(
Helper.getDecimalPointsForCurrencyPairs(
this.props.rowData.currencyPair,
),
)
: this.props.rowData.bid}
</Text>
<Text style={[styles.width60, styles.customFont]}>
{Helper.getDecimalPointsForCurrencyPairs(
this.props.rowData.currencyPair,
) != -1
? this.props.rowData.offer.toFixed(
Helper.getDecimalPointsForCurrencyPairs(
this.props.rowData.currencyPair,
),
)
: this.props.rowData.offer}
</Text>
<Icon
name="ios-stats-chart"
style={[styles.gridiconstyle, styles.width30]}
/>
</View>
</TouchableHighlight>
) : (
<TouchableHighlight
underlayColor={'#000000'}
style={{backgroundColor: '#333e48'}}
delayLongPress={50}
{...this.props.sortHandlers}>
<View style={[styles.rowstyle]}>
<HTMLText
style={[
styles.width100,
styles.customFont,
styles.textGold,
]}
html={Helper.selectProductNameBaseOnLang(
this.props.appLanguage,
this.props.rowData,
)}
/>
<Text style={[styles.width60, styles.customFont]}>
{Helper.getDecimalPointsForCurrencyPairs(
this.props.rowData.currencyPair,
) != -1
? this.props.rowData.bid.toFixed(
Helper.getDecimalPointsForCurrencyPairs(
this.props.rowData.currencyPair,
),
)
: this.props.rowData.bid}
</Text>
<Text style={[styles.width60, styles.customFont]}>
{Helper.getDecimalPointsForCurrencyPairs(
this.props.rowData.currencyPair,
) != -1
? this.props.rowData.offer.toFixed(
Helper.getDecimalPointsForCurrencyPairs(
this.props.rowData.currencyPair,
),
)
: this.props.rowData.offer}
</Text>
<Icon
name="ios-stats-chart"
style={[
styles.gridiconstyle,
styles.width30,
styles.desabled,
]}
/>
</View>
</TouchableHighlight>
)}
</View>
{/* </SwipeableItem> */}
</Swipeout>
</ScaleDecorator>
</View>
);
},
});
module.exports = RowComponent;

Return next page and close current page after loads in React Native

I'm newbie in React-native and I'm confused on how can I pass the parameter to another js file when returning a View, The second problem , The code I used below is when returning home the previous page(login) didn't close or gone and the home didn't view properly. I'm aware using react-nativigation but it's hard for me to implement but is there any other way to direct login when it loads? please need some help for this , here's my code,
Login.js After login from googlesignin when the state loaded it goes to another activity
import { Home } from "../screens"
render() {
return (
<View style={styles.container}>
<GoogleSigninButton
style={{ width: 222, height: 48 }}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={this.signIn}
/>
{this.state.loaded ?
<View style={{ width: 160, marginTop: 10 }}>
{renderLogin(this)} //return some value
</View>
: <Text>Not signIn</Text>}
</View>
);
}
}
function renderLogin(ts) {
return (
<Home /> // i want to pass value to home js example: 'ts.state.userGoogleInfo.user.photo'
)
}
Whole code in Login.js
import React, { Component } from 'react';
import { View, StyleSheet, ToastAndroid, Button, Text, Image } from "react-native";
import { Home } from "../screens"
import {
GoogleSignin,
GoogleSigninButton,
statusCodes,
} from '#react-native-community/google-signin';
GoogleSignin.configure({
webClientId: '2622122222248-3v21124124124124.apps.googleusercontent.com',
offlineAccess: true, // if you want to access Google API on behalf
});
class Login extends Component {
constructor(props) {
super(props)
this.state = {
userGoogleInfo: {},
loaded: false
}
}
static navigationOptions = {
title: 'Login',
};
signIn = async () => {
try {
console.log("Processing");
await GoogleSignin.hasPlayServices();
const userInfo = await GoogleSignin.signIn();
this.setState({
userGoogleInfo: userInfo,
loaded: true
})
console.log(this.state.userGoogleInfo);
console.log(this.state.userGoogleInfo.user.name)
console.log(this.state.userGoogleInfo.user.email)
} catch (error) {
if (error.code === statusCodes.SIGN_IN_CANCELLED) {
console.log("e 1");
} else if (error.code === statusCodes.IN_PROGRESS) {
console.log("e 2");
} else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
console.log("e 3");
} else {
console.log(error.message);
}
}
};
render() {
return (
<View style={styles.container}>
<GoogleSigninButton
style={{ width: 222, height: 48 }}
size={GoogleSigninButton.Size.Wide}
color={GoogleSigninButton.Color.Dark}
onPress={this.signIn}
/>
{this.state.loaded ?
<View style={{ width: 160, marginTop: 10 }}>
{renderLogin(this)}
</View>
: <Text>Not signIn</Text>}
</View>
);
}
}
function renderLogin(ts) {
return (
<Home />
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#000000',
padding: 15,
},
buttons: {
width: 20
}
});
export default Login;
Home.js
import React from 'react';
import {
StyleSheet,
View,
Text,
ScrollView,
FlatList,
TouchableOpacity,
Image,
ImageBackground,
LogBox
} from 'react-native';
import { PriceAlert, TransactionHistory } from "../components"
import { dummyData, COLORS, SIZES, FONTS, icons, images} from '../constants';
const Home = ({ navigation }) => {
const [trending, setTrending] = React.useState(dummyData.trendingCurrencies)
const [transactionHistory, setTransactionHistory] = React.useState(dummyData.transactionHistory)
function renderHeader(){
const renderItem = ({item, index}) =>(
<TouchableOpacity
style={{
width:155,
paddingVertical:SIZES.padding,
paddingHorizontal:SIZES.padding,
marginLeft: index == 0 ? SIZES.padding : 0,
marginRight: SIZES.radius,
borderRadius: 15,
backgroundColor: COLORS.white
}}
onPress={() => navigation.navigate("CryptoDetail", {currency:item})}
>
{/* Currency*/}
<View style={{ flexDirection:'row'}}>
<View>
<Image
source={item.image}
resizeMode="cover"
style={{
marginTop: 5,
width: 25,
height: 25
}}
/>
</View>
<View style={{marginLeft: SIZES.base}}>
<Text style={{...FONTS.h3}}>{item.currency}</Text>
<Text style={{ color:COLORS.gray, ...FONTS.body3 }}></Text>
</View>
</View>
{/* value*/}
{/* <View style={{ marginTop:SIZES.radius}}> */}
{/* <Text style={{...FONTS.h6}}>₱{item.amount}</Text> */}
{/* <Text style={{color: item.type =="I" ? COLORS.green : COLORS.red, ...FONTS.h5}}>₱{item.amount}</Text> */}
{/* </View> */}
</TouchableOpacity>
)
return(
<View
style={{
width: "100%",
height: 210,
...styles.shadow
}}
>
<ImageBackground
source={images.banner}
resizeMode="cover"
style={{
flex: 1,
alignItems:'center'
}}
>
{/* Header Bar */}
<View
style={{
marginTop:SIZES.padding *1,
width: "100%",
alignItems: "flex-end",
paddingHorizontal: SIZES.padding
}}
>
<TouchableOpacity
style={{
width: 20,
height: 20,
alignItems: "center",
justifyContent:"center"
}}
onPress={() => console.log("Notification on pressed")}
>
<Image
source={icons.notification_white}
resizeMode="contain"
style={{flex: 1}}
/>
</TouchableOpacity>
</View>
{/* Balance */}
<View
style={{
alignItems: 'center',
justifyContent:'center'
}}
>
<Text style={{ color: COLORS.white, ...FONTS.h3}}>Available Balance</Text>
<Text style={{ marginTop:SIZES.base, color:COLORS.white, ...FONTS.h2}}>₱{dummyData.portfolio.balance}</Text>
<Text style={{color:COLORS.white, ...FONTS.body5}}>{dummyData.portfolio.changes} Last 24 hours</Text>
</View>
{/* Trending */}
<View
style={{
position:'absolute',
bottom: "-30%"
}}
>
<Text style={{ marginLeft:SIZES.padding,
color: COLORS.white, ...FONTS.h3 }}>Dashboard</Text>
<FlatList
contentContainerStyle={{marginTop:SIZES.base}}
data={trending}
renderItem={renderItem}
keyExtractor={item => `${item.id}`}
horizontal
showsHorizontalScrollIndicator={false}
/>
</View>
</ImageBackground>
</View>
)
}
function renderAlert(){
return (
<PriceAlert/>
)
}
function renderNotice(){
return (
<View
style={{
marginTop:SIZES.padding-6,
marginHorizontal: SIZES.padding,
padding: 12,
borderRadius:SIZES.radius,
backgroundColor:COLORS.secondary,
...styles.shadow
}}
>
<Text style={{color:COLORS.white, ...FONTS.h4}}>Announcement:</Text>
<Text style={{marginTop:SIZES.base, color:COLORS.white, ...FONTS.body4, lineHeight:18}}>We offer you an application to guide and track your data.
Learn how to use this application by reading instructions and guide.
</Text>
<TouchableOpacity
style={{
marginTop:SIZES.base
}}
onPress={()=> console.log("Learn More")}
>
<Text style={{ textDecorationLine: 'underline',
color:COLORS.green, ...FONTS.h4}}>Learn more
</Text>
</TouchableOpacity>
</View>
)
}
function renderTransactionHistory(){
return (
<TransactionHistory
customContainerStyle={{ ...styles.shadow}}
history={transactionHistory}
/>
)
}
return (
<ScrollView>
<View style={{ flex:1, paddingBottom:130 }}>
{renderHeader()}
{renderAlert()}
{renderNotice()}
{renderTransactionHistory()}
</View>
</ScrollView>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
},
shadow: {
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 4,
},
shadowOpacity: 0.30,
shadowRadius: 4.65,
elevation: 8,
}
})
export default Home;
Apps.js
import React from 'react';
import { Transaction, TevDetail, Login } from "./screens";
import { createStackNavigator } from "#react-navigation/stack";
import { NavigationContainer } from '#react-navigation/native';
import SplashScreen from 'react-native-splash-screen';
import Tabs from "./navigation/tabs";
const Stack = createStackNavigator();
const App = () => {
React.useEffect(() => {
SplashScreen.hide()
}, [])
return (
<NavigationContainer>
<Stack.Navigator
screenOptions={{
headerShown: false
}}
initialRouteName={'Login'}
>
<Stack.Screen
name="Home"
component={Tabs}
/>
<Stack.Screen
name="TevDetail"
component={TevDetail}
/>
<Stack.Screen
name="Transaction"
component={Transaction}
/>
<Stack.Screen
name="Login"
component={Login}
/>
</Stack.Navigator>
</NavigationContainer>
)
}
export default App;

React Native WebView reload on state change

Error on line 9
I need to change the state (url) for the WebView.
These is an error for my first function...
Any help would be appreciated.
enter image description here
I'm fairly new to this
I need the TouchableOpacity to change the url state on touch.
import React, { Component } from 'react';
import {View, WebView, Dimensions, AppRegistry, StatusBar, Text, TouchableOpacity} from 'react-native';
let ScreenHeight = Dimensions.get("window").height;
let ScreenWidth = Dimensions.get("window").width;
export default class dynamix extends Component {
function setState(obj){
this.state.url = obj.url;
}
function onPressButtonURL1(){
this.setState({ url: 'url1'})
}
function onPressButtonURL2(){
this.setState({ url: 'url2'})
}
function onPressButtonURL3(){
this.setState({ url: 'url3'})
}
render() {
return (
<View>
<View style={{height:ScreenHeight-100, width:ScreenWidth}}>
<WebView style={{
paddingTop:25,
backgroundColor: '#f8f8f8',
width:ScreenWidth,
height:ScreenHeight,
}}
source={{ url: this.state.url }}
/>
<StatusBar hidden />
</View>
<View style={{
backgroundColor:'#131313',
height:100,
width:ScreenWidth
}}>
<View style={{
width:ScreenWidth
}}>
<TouchableOpacity onPress={() => onPressButtonURL1()}><Text style={{color:'#fff', padding:10,fontSize:15}}>"text1"</Text></TouchableOpacity>
<TouchableOpacity onPress={() => onPressButtonURL2()}><Text style={{color:'#fff', padding:10,fontSize:15}}>"text2"</Text></TouchableOpacity>
<TouchableOpacity onPress={() => onPressButtonURL3()}><Text style={{color:'#fff', padding:10,fontSize:15}}>"text3"</Text></TouchableOpacity>
</View>
</View>
</View>
);
}
}
AppRegistry.registerComponent('dynamix', () => dynamix);
import React, { Component } from 'react';
import { Text, View, WebView, TouchableOpacity, Dimensions } from 'react-native';
const {
height: ScreenHeight,
width: ScreenWidth
} = Dimensions.get('window');
export default class dynamix extends Component {
constructor() {
super();
this.state = {
url: 'https://www.google.co.uk'
}
}
onPressButtonURL = (url) => {
this.setState({ url })
}
render() {
return (
<View>
<View style={{height:ScreenHeight-100, width:ScreenWidth}}>
<Text>{this.state.url}</Text>
<WebView style={{
paddingTop:25,
backgroundColor: '#f8f8f8',
width:ScreenWidth,
height:ScreenHeight,
}}
source={{ uri: this.state.url }}
/>
</View>
<View style={{
backgroundColor:'#131313',
height:100,
width:ScreenWidth
}}>
<View style={{
width:ScreenWidth
}}>
<TouchableOpacity onPress={() => this.onPressButtonURL('https://stackoverflow.com')}><Text style={{color:'#fff', padding:10,fontSize:15}}>text1</Text></TouchableOpacity>
<TouchableOpacity onPress={() => this.onPressButtonURL('https://www.google.com')}><Text style={{color:'#fff', padding:10,fontSize:15}}>text2</Text></TouchableOpacity>
<TouchableOpacity onPress={() => this.onPressButtonURL('https://bbc.co.uk')}><Text style={{color:'#fff', padding:10,fontSize:15}}>text3</Text></TouchableOpacity>
</View>
</View>
</View>
);
}
}
AppRegistry.registerComponent('dynamix', () => dynamix);
Edit: I have just seen your attached image, the keyword function is throwing you the error.
If you go to here and paste in
class Person {
function setName(name) {
this.name = name;
}
}
You'll see the Unexpected token (2:11) error. Removing the function keyword works.

Categories