React Native WebView reload on state change - javascript

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.

Related

WebView does not appear when onPress() triggered

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>
);
}
}

Unable to use onPress for navigation inside of nested Screen React Native

Let me begin by saying that I am fairly new to React Native. I have an AppNavigation.js component that holds nested functions for swapping tabbed views using createBottomTabNavigator() -- The issue I am having, is I cannot use a button that I created inside of one of the nested components for the Dashboard Screen. Its stating that my hook is being incorrectly used. I tried numerous approaches from stack overflow sources. Yet, I cannot get the button to navigate to the view after clicking it. How do I navigate to other components while using a nested component for the Screen component?
ERROR:
ReferenceError: Can't find variable: navigation
ProfileCard.js
import React, {Component} from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Dimensions, Image, AsyncStorage} from 'react-native';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'
import axios from 'axios'
class ProfileCard extends Component {
constructor(props) {
super(props);
this.survey_form = {};
this.state = {
hasSurveyProfile: false
};
}
componentDidMount() {
this.getToken()
.then(obj => axios.get(`http://127.0.0.1:3000/api/v1/check_for_survey_form/${obj.user_id}`, {headers: {Accept: 'application/json', 'X-User-Email': `${obj.email}`, 'X-User-Token': `${obj.authentication_token}`}}))
.then(response => {
this.setState({survey_form: JSON.stringify(response.data)});
this.setState({hasSurveyProfile: true});
})
.catch(error => {
if (error.response.status == 404) {
this.setState({hasSurveyProfile: false})
}
});
}
async getToken(user) {
try {
/////
} catch (error) {
console.log("Something went wrong", error);
}
}
render() {
const { navigation } = this.props;
return(
<View style={{paddingVertical: 5, paddingHorizontal: 5}}>
<View style={{backgroundColor: '#fff', width: Dimensions.get('window').width * .9, minHeight: 50, padding: 2, borderColor: 'gray', borderRadius: 4, borderWidth: 1}}>
<View style={{flexDirection: "row"}}>
<View style={{flex: 1}}>
<Text style={{textAlign: 'center', fontWeight: '500', fontSize: 16}}>Survey Profile</Text>
<Text style={{textAlign: 'center', fontSize: 10}}>Complete your Survey!</Text>
{
(this.state.hasSurveyProfile == false)
? <TouchableOpacity style={styles.buttoncontainer} onPress={() => navigation.navigate('StartSurvey')}>
<Text style={styles.buttontext}>Start Survey</Text>
</TouchableOpacity>
: <TouchableOpacity style={styles.buttoncontainer}>
<Text style={styles.buttontext}>Edit Survey</Text>
</TouchableOpacity>
}
</View>
</View>
</View>
</View>
)
}
}
export default ProfileCard;
AppNavigation.js
import React from 'react'
import { Text, TouchableOpacity, Image, View } from 'react-native'
import {NavigationContainer} from '#react-navigation/native';
import {createBottomTabNavigator} from '#react-navigation/bottom-tabs'
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'
import ProfileCard from '../containers/UserProfileCard';
function DashboardScreen() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<View style={{flex: 1, alignItems: 'center'}}>
<ProfileCard />
</View>
</View>
);
}
function MessagesScreen() {
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text>Messages!</Text>
</View>
);
}
const Tab = createBottomTabNavigator();
function MyTabs() {
return (
<Tab.Navigator>
<Tab.Screen
name="Dashboard"
component={DashboardScreen}
options={{
tabBarLabel: 'Dashboard',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="home" color={color} size={26} />
),
}}
/>
<Tab.Screen
name="Messages"
component={MessagesScreen}
options={{
tabBarLabel: 'Messages',
tabBarIcon: ({ color }) => (
<MaterialCommunityIcons name="email-outline" color={color} size={26} />
),
}}
/>
</Tab.Navigator>
);
}
export default function AppNavigation() {
return (
<NavigationContainer>
<MyTabs />
</NavigationContainer>
);
}
StartSurvey.js (Unable to get here from button click)
import React, {Component} from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Dimensions, Image, AsyncStorage} from 'react-native';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons'
import axios from 'axios';
import { initMiddleware } from 'devise-axios'
initMiddleware({storage: AsyncStorage})
class StartSurvey extends Component {
constructor(props) {
super(props);
this.state = {
user_id: ''
}
}
componentDidMount() {
this.getToken()
.then(obj => axios.get(`http://127.0.0.1:3000/api/v1/retrieve_user/${obj.user_id}`, {headers: {Accept: 'application/json', 'X-User-Email': `${obj.email}`, 'X-User-Token': `${obj.authentication_token}`}}))
.then(response => {
this.setState({ user: JSON.stringify(response.data)});
this.setState({user_id: JSON.parse(this.state.user).id.toString()})
})
.catch(error => {
console.error(error);
});
}
async getToken(user) {
try {
let userData = await AsyncStorage.getItem("userData");
let data = JSON.parse(userData);
let user = JSON.parse(data)
let userObj = {user_id: JSON.stringify(user.data.data.id), email: JSON.stringify(user.data.data.email), authentication_token: JSON.stringify(user.data.data.authentication_token)}
return userObj
} catch (error) {
console.log("Something went wrong", error);
}
}
render() {
return(
<View style={{paddingVertical: 5, paddingHorizontal: 5}}>
<View style={{backgroundColor: '#fff', width: Dimensions.get('window').width * .9, minHeight: 50, padding: 2, borderColor: 'gray', borderRadius: 4, borderWidth: 1}}>
<Text>Hello Survey!</Text>
</View>
</View>
)
}
}
export default StartSurvey;
So it doesn't look like you're actually passing the navigation prop into the <ProfileCard /> component.
You can pass the navigation function to the <DashboardScreen /> component.
Then inside of the <DashboardScreen /> component, you can pass the same navigation function to the <ProfileCard /> component.
So the code ends up looking something like:
<DashboardScreen navigation={navigation} />
Later on...
<ProfileCard navigation={navigation} />
EDIT:
You'll likely need to change the way you're passing the <DashboardScreen /> component to the <Tab.Screen> component, making it a child of <Tab.Screen>
Something that looks like:
<Tab.Screen>
// Your other props here...
<DashboardScreen navigation={navigation} />
</Tab.Screen>

Search bar glitching out in React Native

I'm making a search bar that displays results live. I've managed to do it properly utilizing SearchBar from 'react-native-elements'. Firstly I had it written as a class component, but decided to rewrite it as a functional component. After rewriting it I'm encountering a bug where the keyboard closes after one letter as seen in the video here
Here is the code of the component
import React, { Component, useEffect, useState } from "react";
import { View, Text, FlatList, TextInput, ListItem } from "react-native";
import { SearchBar } from "react-native-elements";
import { Button } from 'react-native-paper'
import Header from "../navigation/Header";
export default function AktSelect() {
const [data, setData] = useState([])
const [value, setValue] = useState('')
const [akt, setAkt] = useState([])
useEffect(() => {
fetch("http://192.168.5.12:5000/aktprikaz", {
method: "get"
})
.then(res => res.json())
.then(res => setAkt(res));
}, []);
function renderSeparator() {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#CED0CE"
}}
/>
);
}
function searchItems(text) {
const newData = akt.filter(item => {
const itemData = `${item.title.toUpperCase()}`;
const textData = text.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setData(newData)
setValue(text)
}
function renderHeader() {
return (
<SearchBar
placeholder=" Type Here...Key word"
onChangeText={text => searchItems(text)}
value={value}
lightTheme={true}
/>
);
}
return (
<View
style={{
flex: 1,
width: "98%",
alignSelf: "center",
justifyContent: "center"
}}
>
<Header title='Pretraživanje aktivnosti' />
<FlatList
data={data}
renderItem={({ item }) => (
<View style={{flex: 1}}>
<Text style={{ padding: 10 }}>{item.title} </Text>
<View style={{flexDirection:'row'}}>
<Text style={{ padding: 10 }}>{item.start_time} </Text>
<Button style={{justifyContent: 'flex-end', alignContent: 'flex-end', width:'30%'}} mode='contained' onPress={() => console.log('hi')}>hi</Button>
</View>
</View>
)}
keyExtractor={item => item.id.toString()}
ItemSeparatorComponent={renderSeparator}
ListHeaderComponent={renderHeader}
/>
</View>
);
}
The old class component can be found here

Getting JSON Parse error: Unexpected identifier "undefined" when using React native & React navigation?

I am pretty new to React Native, so if the question seems stupid i am sorry in advance, i have been trying for hours to get this to work before asking this question.
I am trying to pass data from a text input to the next screen using firebase database.
I keep getting the error JSON Parse error: Unexpected identifier "undefined", I have attached below my two files, one with the text input (InputForm.js) and the other one which i want to show that data on the screen (ASTConfig1screen)
If anyone can help with this you really are a superstar!
InputForm.js
import React, { Component } from 'react';
import { StyleSheet, ScrollView, ActivityIndicator, View, TextInput } from 'react-native';
import { Button } from 'react-native-elements';
import firebase from '../Firebase';
import { withNavigation } from 'react-navigation';
class InputForm extends Component {
constructor() {
super();
this.ref = firebase.firestore().collection('boards');
this.state = {
name: '',
inventoryclass: '',
outlet: '',
isLoading: false,
};
}
updateTextInput = (text, field) => {
const state = this.state
state[field] = text;
this.setState(state);
}
saveBoard() {
this.setState({
isLoading: true,
});
this.ref.add({
name: this.state.name,
inventoryclass: this.state.inventoryclass,
outlet: this.state.outlet,
}).then((docRef) => {
this.setState({
name: '',
outlet: '',
inventoryclass: '',
isLoading: false,
});
this.props.navigation.navigate('ASTConfig1');
})
.catch((error) => {
console.error("Error adding document: ", error);
this.setState({
isLoading: false,
});
});
}
render() {
if(this.state.isLoading){
return(
<View style={styles.activity}>
<ActivityIndicator size="large" color="#ffa500"/>
</View>
)
}
return (
<ScrollView style={styles.container}>
<View style={styles.subContainer}>
<TextInput style={styles.inputtext}
placeholder={'Name'}
placeholderTextColor="white"
value={this.state.name}
onChangeText={(text) => this.updateTextInput(text, 'name')}
/>
</View>
<View style={styles.subContainer}>
<TextInput style={styles.inputtext}
multiline={true}
numberOfLines={4}
placeholder={'Inventory Class'}
placeholderTextColor="white"
value={this.state.inventoryclass}
onChangeText={(text) => this.updateTextInput(text, 'inventoryclass')}
/>
</View>
<View style={styles.subContainer}>
<TextInput style={styles.inputtext}
placeholder={'Outlet'}
placeholderTextColor="white"
value={this.state.outlet}
onChangeText={(text) => this.updateTextInput(text, 'outlet')}
/>
</View>
<View style={styles.button}>
<Button
large
leftIcon={{name: 'save'}}
title='Save'
onPress={() => this.saveBoard()} />
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 20
},
subContainer: {
flex: 1,
marginBottom: 20,
padding: 5,
borderBottomWidth: 2,
borderBottomColor: '#CCCCCC',
},
inputtext: {
color: 'white',
fontSize: 20
},
activity: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
}
})
export default withNavigation(InputForm);
and this is where i would like to show the data on this screen
ASTConfig1.js
import React from 'react';
import {
View,
Text,
StyleSheet,
Button,
ImageBackground,
StatusBar,
SafeAreaView,
TextInput,
ScrollView,
UIManager,
ActivityIndicator
}
from 'react-native';
import {AccordionList} from "accordion-collapse-react-native";
import { Separator } from 'native-base';
import {widthPercentageToDP as wp, heightPercentageToDP as hp} from 'react-native-responsive-screen';
import firebase from '../Firebase';
import Logo from '.././components/Logo';
import Colors from '.././constants/Colors';
import Search from '.././components/Search';
import InputForm from '.././components/InputForm';
class ASTConfig1Screen extends React.Component {
static navigationOptions = {
title: 'ASTConfig1',
};
constructor(props) {
super(props);
this.state= {
isLoading: true,
board: {},
key: '',
status:true,
text: '',
list:[
{
title: 'Getting Started',
body: 'React native Accordion/Collapse component, very good to use in toggles & show/hide content'
},
{
title: 'Components',
body: 'AccordionList,Collapse,CollapseHeader & CollapseBody'
},
{
title: 'Test',
body: 'AccordionList,Collapse,CollapseHeader & CollapseBody'
}
],
}
}
componentDidMount() {
const { navigation } = this.props;
const ref = firebase.firestore().collection('boards').doc(JSON.parse(navigation.getParam('boardkey')));
ref.get().then((doc) => {
if (doc.exists) {
this.setState({
board: doc.data(),
key: doc.id,
isLoading: false
});
} else {
console.log("No such document!");
}
});
}
_head(item){
return(
<Separator bordered style={{alignItems:'center'}}>
<Text>{item.title}</Text>
</Separator>
);
}
_body(item){
return (
<View style={{padding:10}}>
<Text style={{textAlign:'center'}}>{item.body}</Text>
</View>
);
}
ShowHideTextComponentView = () =>{
if(this.state.status == true)
{
this.setState({status: false})
}
else
{
this.setState({status: true})
}
}
render() {
if(this.state.isLoading){
return(
<View style={styles.activity}>
<ActivityIndicator size="large" color="#0000ff" />
</View>
)
}
return (
<View style={styles.screen}>
<ImageBackground
source={require('.././assets/Img/BackGround2.png')}
style={styles.background}>
</ImageBackground>
<SafeAreaView>
<View style={{flex: 1, justifyContent: 'space-between', width: wp('80%')}}>
<View style={styles.logotop}>
<Logo/>
</View>
<View style={styles.editstock}>
<Text style={styles.editstocktext}>EDIT STOCK LIST:</Text>
</View>
{/*Start of 3 buttons Firebase*/}
<View style={styles.three}>
<View style={styles.edit1}>
<Text style={styles.textheader}>{this.state.board.name}</Text>
<Button style={styles.edit} title='Edit' ></Button>
</View>
<View style={{padding: 3}}></View>
<View style={styles.edit2}>
<Text style={styles.text}>{this.state.board.inventoryclass}</Text>
<Button style={styles.edit} title='Edit' ></Button>
</View>
<View style={styles.edit3}>
<Text style={styles.text}>{this.state.board.outlet}</Text>
<Button style={styles.edit} title='Edit' ></Button>
</View>
</View>
{/*End of 3 buttons Firebase*/}
{/*Start of AccordionList*/}
<ScrollView>
<View style={styles.middle}>
<AccordionList
list={this.state.list}
header={this._head}
body={this._body}
/>
</View>
</ScrollView>
{/*End of AccordionList*/}
{/*Start of Search*/}
<View>
{
this.state.status ? null : <View style={styles.bottom}>
<Text style={styles.textbottom}>SEARCH FOR NEW ITEMS:</Text>
<Search />
</View>
}
<Button title="ADD" onPress={this.ShowHideTextComponentView} />
</View>
</View>
</SafeAreaView>
</View>
);
};
};
{/*End of Search*/}
export default ASTConfig1Screen;
but it returns the error - Error adding document: [SyntaxError: SyntaxError: SyntaxError: JSON Parse error: Unexpected identifier "undefined"
in inputform.js saveBoard function you should
this.props.navigation.navigate('Details', {
'ASTConfig1': docRef
});
and remove JSON.parse form other file

How to use CardView in React-native while rendering data?

I get some JSON array from API calling and I want to show them in a list using CardView. But while I am using the CardView tag, it keeps rendering but not showing the data in card. There is nothing wrong with fetching the data as I logged them in console and printed the values.
If, I remove the cardView tag then it works well.
I installed the CardView component using following command-
npm install react-native-cardview --save
I took help from the site-
https://www.npmjs.com/package/react-native-cardview
But it is not working as it is mentioned. So, here, I have provided the code-
import React from 'react';
import { StyleSheet, Text, View, Image, AsyncStorage, ActivityIndicator, TouchableOpacity, ToastAndroid, FlatList } from 'react-native';
import {Icon, Button, Container, Header, Content, Left} from 'native-base';
import CustomHeader from './CustomHeader';
import CardView from 'react-native-cardview';
let jwt=''
class NoteMeHome extends React.Component {
state = {
getValue: '',
dataSource:[],
isLoading: true
}
componentDidMount() {
AsyncStorage.getItem("token").then(value => {
const url = 'my url';
return fetch(url, {
method: 'GET',
headers: new Headers({
'Content-Type' : 'application/json',
'token': 'abc',
'jwt': value
})
})
.then((response)=> response.json() )
.then((responseJson) => {
console.log('####:'+responseJson[0].title)
this.setState({
dataSource: responseJson,
isLoading: false,
getValue: value
})
})
.catch((Error) => {
console.log(Error)
})
}
)}
static navigationOptions = ({navigation}) => ({
title: "Home",
headerLeft: <Icon name="ios-menu" style={{paddingLeft:10}}
onPress={()=>navigation.navigate('DrawerOpen')}/>,
drawerIcon:
<Image source={{uri: 'https://png.icons8.com/message/ultraviolet/50/3498db'}}
style={styles.icon}
/>
})
render() {
const { getValue } = this.state;
return(
this.state.isLoading
?
<View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
<ActivityIndicator size="large" color="#330066" animating/>
</View>
:
<Container>
<CustomHeader
title="Home"
drawerOpen={()=>this.props.navigation.navigate('DrawerOpen')}
/>
<View>
<FlatList
data={this.state.dataSource}
renderItem={this.renderItem}
keyExtractor = {(item, index) => index+""}
ItemSeparatorComponent={this.renderSeparator}
/>
</View>
</Container>
)
}
renderSeparator = ()=> {
return (
<View style={{height:1, width:'100%', backgroundColor:'black'}}>
</View>
)
}
renderItem = ({item}) => {
return(
<TouchableOpacity style={{flex:1, flexDirection:'row'}}
onPress= {() => ToastAndroid.show(item.title, ToastAndroid.SHORT)}
>
<CardView
cardElevation={3}
cardMaxElevation={2}
cornerRadius={5}
paddingBottom={10}
style={{justifyContent:'center',margin:2,backgroundColor:'white'}}
// height='auto' or you can also specify the height in number as per requirement
>
<View style={{padding:10}}>
<Image style={{width:80, height:80, margin:5}}
source={{uri: 'https://png.icons8.com/message/ultraviolet/50/3498db'}}
/>
<View style={{flex:1, justifyContent:'center', marginLeft:5}}>
<Text style={{fontSize:18, color:'green', marginBottom:10}}>
{item.category}
</Text>
<Text style={{fontSize:18, color:'red', marginBottom:10}}>
{item.title}
</Text>
</View>
</View>
</CardView>
</TouchableOpacity>
)
}
}
const styles = StyleSheet.create({
icon:{
height: 24,
width: 24
},
container:{
flex:1,
backgroundColor:'#fff'
}
})
export default NoteMeHome;
So, it would be very nice if someone helps me to know how I can show the item lists in a cardView.

Categories