Code:
import React, { Component,useState } from 'react';
import {
StyleSheet,
View,
TouchableHighlight,
Text,
ToastAndroid,
ScrollView,
Modal,Button
} from 'react-native';
import ProgressCircle from 'react-native-progress-circle'
import AutoTags from 'react-native-tag-autocomplete';
import firebase from '../config';
import { TabView, SceneMap } from 'react-native-tab-view';
const db= firebase.database();
let itemsRef = db.ref('/dataset');
let input = db.ref('/tags');
let disease=[];
itemsRef.limitToFirst(10).on('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
disease.push(childSnapshot.val().Disease);
});
});
let addItem = item => {
input.push({
userSymptom: item
});
};
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
tagsSelected:[],
storedTags:[],
index: 0,
routes: [
{ key: 'first', title: 'First' },
{ key: 'second', title: 'Second' },
{ key: 'third', title: 'Third'}],
modalVisible: false,
};
}
componentDidMount(){
let storedTags=[];
itemsRef.on('value', (snapshot) => {
snapshot.forEach((childSnapshot) => {
storedTags.push({'name':childSnapshot.val().Symptom});
});
});
let userSymptoms=[];
input.limitToLast(1).on('value', (snapshot)=>{
snapshot.forEach((childSnapshot)=>{
childSnapshot.val().userSymptom.forEach(element=>{
userSymptoms.push(element)
})
})
})
this.setState({ tagsSelected:userSymptoms})
this.setState({ storedTags: storedTags})
}
setModalVisible(visible){
this.setState({ modalVisible: visible });
}
Modal=()=>(
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={this.state.modalVisible}
onRequestClose={() => {
console.log("Modal has been closed.");
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Hello World!</Text>
<TouchableHighlight
style={{ ...styles.openButton, backgroundColor: "#2196F3" }}
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}
>
<Text style={styles.textStyle}>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
</View>
);
FirstRoute = () => (
<ScrollView style={[styles.container, { backgroundColor: '#ff4081' }]} >
{this.Modal()}
<TouchableHighlight style={styles.back} onPress={() => {
this.setModalVisible(true);
console.log('Pressed')
}}>
<View style={styles.DisEntry}>
<Text style={styles.text}>{disease[0]}</Text>
<ProgressCircle
percent={30}
radius={50}
borderWidth={8}
color="#3399FF"
shadowColor="#999"
bgColor="#fff"
>
<Text style={{ fontSize: 18 }}>{'30%'}</Text>
</ProgressCircle>
</View>
</TouchableHighlight>
</ScrollView>
);
SecondRoute = () => (
<View style={[styles.container, { backgroundColor: '#673ab7' }]}>
</View>
);
ThirdRoute = () => (
<View style={[styles.container, { backgroundColor: '#673ab7' }]}>
</View>
);
handleSubmit = () => {
addItem(this.state.tagsSelected);
ToastAndroid.show('Symptoms saved successfully', ToastAndroid.SHORT)
};
handleDelete = index => {
let tagsSelected = this.state.tagsSelected;
tagsSelected.splice(index, 1);
this.setState({ tagsSelected });
}
handleAddition = suggestion => {
this.setState({ tagsSelected: this.state.tagsSelected.concat([suggestion]) });
}
_handleIndexChange = index => this.setState({ index });
_renderScene = SceneMap({
first: this.FirstRoute,
second: this.SecondRoute,
third: this.ThirdRoute,
});
render() {
return (
<View style={styles.container}>
<View style={styles.row}>
<View style={styles.autocompleteContainer}>
<AutoTags
suggestions={this.state.storedTags}
tagsSelected={this.state.tagsSelected}
handleAddition={this.handleAddition}
handleDelete={this.handleDelete}
placeholder="Add a Symptom.." />
</View>
<TouchableHighlight
style={styles.button}
underlayColor="blue"
onPress={this.handleSubmit}>
<Text style={styles.buttonText}>Add</Text>
</TouchableHighlight>
</View>
<TabView
style={styles.tab}
navigationState={this.state}
renderScene={this._renderScene}
renderTabBar={this._renderTabBar}
onIndexChange={this._handleIndexChange}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex:1,
},
row:{
flexDirection:"row"
},
DisEntry:{
flexDirection:"row",
backgroundColor:'white',
borderColor: 'black',
borderWidth: 1,
borderRadius: 5,
padding: 2,
},
back:{
backgroundColor: 'blue'
},
text:{
flex:1,
},
button:{
flex:0,
backgroundColor:'white',
borderColor: 'black',
borderWidth: 1,
borderRadius: 5,
padding: 2,
justifyContent:'flex-end',
height:30,
justifyContent:'center',
},
autocompleteContainer: {
flex:1,
justifyContent:'flex-start',
marginBottom:10
},
tab:{
flex:1,
},
centeredView: {
flex: 1,
justifyContent: "center",
alignItems: "center",
marginTop: 22
},
modalView: {
margin: 20,
backgroundColor: "white",
borderRadius: 20,
padding: 35,
alignItems: "center",
shadowColor: "#000",
shadowOffset: {
width: 0,
height: 2
},
shadowOpacity: 0.25,
shadowRadius: 3.84,
elevation: 5
},
openButton: {
backgroundColor: "#F194FF",
borderRadius: 20,
padding: 10,
elevation: 2
},
textStyle: {
color: "white",
fontWeight: "bold",
textAlign: "center"
},
modalText: {
marginBottom: 15,
textAlign: "center"
}
});
I am facing the problem that i am unable to toggle the Modal visibility when i click the touchable highlight. Please tell me where is the issue in my code as when i change the state of my modalVisible to true the modal shows finely
.....................................................................................................
If i'm not mistaken Modal has to be inside of return()
class App extends Component {
state = {
modalVisible: false
};
setModalVisible = (visible) => {
this.setState({ modalVisible: visible });
}
render() {
const { modalVisible } = this.state;
return (
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Hello World!</Text>
<TouchableHighlight
style={{ ...styles.openButton, backgroundColor: "#2196F3" }}
onPress={() => {
this.setModalVisible(!modalVisible);
}}
>
<Text style={styles.textStyle}>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
<TouchableHighlight
style={styles.openButton}
onPress={() => {
this.setModalVisible(true);
}}
>
<Text style={styles.textStyle}>Show Modal</Text>
</TouchableHighlight>
</View>
);
}
}
Related
enter image description here Iam new with react native,so maybe my question seems silly to all excepts.I want to add current time in text input.(i designd todo app,that show the todo list,now i want to show time in todo list,for eg i enter todo(complete frontend)and add,that contain complete and delete button,now i want to add time in that(task adding time).my code are following below,
import React from 'react';
import {
StyleSheet,
SafeAreaView,
View,
TextInput,
Text,
FlatList,
TouchableOpacity,
Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '#react-native-async-storage/async-storage';
const COLORS = {primary: '#1f145c', white: '#fff'};
const App = () => {
const \[todos, setTodos\] = React.useState(\[\]);
const \[textInput, setTextInput\] = React.useState('');
React.useEffect(() => {
getTodosFromUserDevice();
}, \[\]);
React.useEffect(() => {
saveTodoToUserDevice(todos);
}, \[todos\]);
const addTodo = () => {
if (textInput == '') {
Alert.alert('Error', 'Please input todo');
} else {
const newTodo = {
id: Math.random(),
task: textInput,
completed: false,
};
setTodos(\[...todos, newTodo\]);
setTextInput('');
}
};
const saveTodoToUserDevice = async todos => {
try {
const stringifyTodos = JSON.stringify(todos);
await AsyncStorage.setItem('todos', stringifyTodos);
} catch (error) {
console.log(error);
}
};
const getTodosFromUserDevice = async () => {
try {
const todos = await AsyncStorage.getItem('todos');
if (todos != null) {
setTodos(JSON.parse(todos));
}
} catch (error) {
console.log(error);
}
};
const markTodoComplete = todoId => {
const newTodosItem = todos.map(item => {
if (item.id == todoId) {
return {...item, completed: true};
}
return item;
});
setTodos(newTodosItem);
};
const deleteTodo = todoId => {
const newTodosItem = todos.filter(item => item.id != todoId);
setTodos(newTodosItem);
};
const clearAllTodos = () => {
Alert.alert('Confirm', 'Clear todos?', \[
{
text: 'Yes',
onPress: () => setTodos(\[\]),
},
{
text: 'No',
},
\]);
};
const ListItem = ({todo}) => {
return (
<View style={styles.listItem}>
<View style={{flex: 1}}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
textDecorationLine: todo?.completed ? 'line-through' : 'none',
}}>
{todo?.task}
</Text>
</View>
{!todo?.completed && (
<TouchableOpacity onPress={() => markTodoComplete(todo.id)}>
<View style={\[styles.actionIcon, {backgroundColor: 'green'}\]}>
<Icon name="done" size={20} color="white" />
</View>
</TouchableOpacity>
)}
<TouchableOpacity onPress={() => deleteTodo(todo.id)}>
<View style={styles.actionIcon}>
<Icon name="delete" size={20} color="white" />
</View>
</TouchableOpacity>
</View>
);
};
return (
<SafeAreaView
style={{
flex: 1,
backgroundColor: 'white',
}}>
<View style={styles.header}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
}}>
TODO APP
</Text>
<Icon name="delete" size={25} color="red" onPress={clearAllTodos} />
</View>
<FlatList
showsVerticalScrollIndicator={false}
contentContainerStyle={{padding: 20, paddingBottom: 100}}
data={todos}
renderItem={({item}) => <ListItem todo={item} />}
/>
<View style={styles.footer}>
<View style={styles.inputContainer}>
<TextInput
value={textInput}
placeholder="Add Todo"
onChangeText={text => setTextInput(text)}
/>
</View>
<TouchableOpacity onPress={addTodo}>
<View style={styles.iconContainer}>
<Icon name="add" color="white" size={30} />
</View>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
footer: {
position: 'absolute',
bottom: 0,
width: '100%',
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 20,
backgroundColor: COLORS.white,
},
inputContainer: {
height: 50,
paddingHorizontal: 20,
elevation: 40,
backgroundColor: COLORS.white,
flex: 1,
marginVertical: 20,
marginRight: 20,
borderRadius: 30,
},
iconContainer: {
height: 50,
width: 50,
backgroundColor: COLORS.primary,
elevation: 40,
borderRadius: 25,
justifyContent: 'center',
alignItems: 'center',
},
listItem: {
padding: 20,
backgroundColor: COLORS.white,
flexDirection: 'row',
elevation: 12,
borderRadius: 7,
marginVertical: 10,
},
actionIcon: {
height: 25,
width: 25,
backgroundColor: COLORS.white,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'red',
marginLeft: 5,
borderRadius: 3,
},
header: {
padding: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
});
export default App;][1]
i got the answer ,answer is following below,
import React from 'react';
import {
StyleSheet,
SafeAreaView,
View,
TextInput,
Text,
FlatList,
TouchableOpacity,
Alert,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import AsyncStorage from '#react-native-async-storage/async-storage';
const COLORS = {primary: '#1f145c', white: '#fff'};
const App = () => {
const [todos, setTodos] = React.useState([]);
const [textInput, setTextInput] = React.useState('');
React.useEffect(() => {
getTodosFromUserDevice();
}, []);
React.useEffect(() => {
saveTodoToUserDevice(todos);
}, [todos]);
const addTodo = () => {
if (textInput == '') {
Alert.alert('Error', 'Please input todo');
} else {
const newTodo = {
id: Math.random(),
task: textInput,
completed: false,
time: getCurrentTime()
};
setTodos([...todos, newTodo]);
setTextInput('');
}
};
const saveTodoToUserDevice = async todos => {
try {
const stringifyTodos = JSON.stringify(todos);
await AsyncStorage.setItem('todos', stringifyTodos);
} catch (error) {
console.log(error);
}
};
const getTodosFromUserDevice = async () => {
try {
const todos = await AsyncStorage.getItem('todos');
if (todos != null) {
setTodos(JSON.parse(todos));
}
} catch (error) {
console.log(error);
}
};
***const getCurrentTime = () => {
let today = new Date();
let date = today.getFullYear()+'-'+(today.getMonth()+1)+'-'+today.getDate();
let time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
let dateTime = date + '/' + time;
return dateTime;
}***
const markTodoComplete = todoId => {
const newTodosItem = todos.map(item => {
if (item.id == todoId) {
return {...item, completed: true};
}
return item;
});
setTodos(newTodosItem);
};
const deleteTodo = todoId => {
const newTodosItem = todos.filter(item => item.id != todoId);
setTodos(newTodosItem);
};
const clearAllTodos = () => {
Alert.alert('Confirm', 'Clear todos?', [
{
text: 'Yes',
onPress: () => setTodos([]),
},
{
text: 'No',
},
]);
};
const comdel = () => {
Alert.alert('select status', 'Complete or Delete', [
{
text: 'Delete',
onPress: () => setTodos([]),
},
{
text: 'Complete',
onPress: () => {markTodoComplete(todo.id)}
},
]);
};
const ListItem = ({todo}) => {
return (
<View style={styles.listItem}>
<View style={{flex: 1}}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
textDecorationLine: todo?.completed ? 'line-through' : 'none',
}}>
{todo?.task}
</Text>
</View>
{/* {!todo?.completed && (
<TouchableOpacity onPress={() => markTodoComplete(todo.id)}>
<View style={[styles.actionIcon, {backgroundColor: 'green'}]}>
<Icon name="done" size={20} color="white" />
</View>
</TouchableOpacity>
)} */}
{/* <TouchableOpacity onPress={() => deleteTodo(todo.id)}>
<View style={styles.actionIcon}>
<Icon name="delete" size={20} color="white" />
</View>
</TouchableOpacity> */}
<View>
<Text>
{todo?.time}
</Text>
</View>
<Icon name="menu" size={40} color="#a9a9a9" onPress={comdel} />
</View>
);
};
return (
<SafeAreaView
style={{
flex: 1,
backgroundColor: 'white',
}}>
<View style={styles.header}>
<Text
style={{
fontWeight: 'bold',
fontSize: 20,
color: COLORS.primary,
}}>
TODO APP
</Text>
<Icon name="delete" size={25} color="red" onPress={comdel} />
</View>
<FlatList
showsVerticalScrollIndicator={false}
contentContainerStyle={{padding: 20, paddingBottom: 100}}
data={todos}
renderItem={({item}) => <ListItem todo={item} />}
/>
<View style={styles.footer}>
<View style={styles.inputContainer}>
<TextInput
value={textInput}
placeholder="Add Todo"
onChangeText={text => setTextInput(text)}
/>
</View>
<TouchableOpacity onPress={addTodo}>
<View style={styles.iconContainer}>
<Icon name="add" color="white" size={30} />
</View>
</TouchableOpacity>
</View>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
footer: {
position: 'absolute',
bottom: 0,
width: '100%',
flexDirection: 'row',
alignItems: 'center',
paddingHorizontal: 20,
backgroundColor: COLORS.white,
},
inputContainer: {
height: 50,
paddingHorizontal: 20,
elevation: 40,
backgroundColor: COLORS.white,
flex: 1,
marginVertical: 20,
marginRight: 20,
borderRadius: 30,
},
iconContainer: {
height: 50,
width: 50,
backgroundColor: COLORS.primary,
elevation: 40,
borderRadius: 25,
justifyContent: 'center',
alignItems: 'center',
},
listItem: {
padding: 40,
backgroundColor: "#d3d3d3",
flexDirection: 'column',
elevation: 12,
borderRadius: 7,
marginVertical: 10,
},
actionIcon: {
height: 25,
width: 25,
backgroundColor: COLORS.white,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'red',
marginLeft: 5,
borderRadius: 3,
},
header: {
padding: 20,
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
});
export default App;
I have a flatlist of cards, and I want a modal to appear when someone presses the card. Pressing the card doesn't seem to do anything though, so I'm wondering what I've done wrong. In my code at the top I have defined the state for the visibility of the modal, if you scroll down to the card you'll see onPress changes the state. Below the card is the actual modal which uses the state of the visible property to display it or not.
Code:
class HomeScreen extends React.Component {
state = {
isModalVisible: false
};
toggleModal = () => {
this.setState({ isModalVisible: !this.state.isModalVisible });
};
render() {
return (
<View style = {{flex:1}}>
<Header
centerComponent={{ text: 'MY MACROS', style: { color: '#fff', letterSpacing: 2} }}
containerStyle={{
backgroundColor: '#5BC0EB',
}}
/>
<Progress.Bar progress={0.7} width={null} height={10} borderRadius = {0} color = {'lightgreen'}/>
<ScrollView>
<FlatList
data = {Macros}
renderItem = {({ item }) => (
<TouchableOpacity>
<Card style = {{justifyContent: 'center', margin: 1, backgroundColor: '#ffff', borderRadius: 25}} onPress = {() => {this.toggleModal}}>
<Card.Content>
<View style = {{flexDirection: 'row', justifyContent: 'space-between'}}>
<View style = {{flexDirection: 'column', justifyContent: 'space-between'}}>
<Title style = {{paddingTop: 20, fontSize: 35, fontWeight: 'bold',color: 'black', letterSpacing: 2}}>{item.total} {item.unit}</Title>
<Text style= {{fontSize: 30, color: 'black', letterSpacing: 2, fontWeight: '100'}}>{item.title}</Text>
</View>
<MainProgress/>
</View>
</Card.Content>
<Card.Actions>
</Card.Actions>
</Card>
<Modal isVisible = {this.state.isModalVisible}>
<View>
<Text>Test</Text>
<Button title = "Cancel" onPress = {this.toggleModal}/>
</View>
</Modal>
</TouchableOpacity>
)}
keyExtractor = {item => item.key}
/>
</ScrollView>
<Button color = {'#5BC0EB'} onPress={popUpForm}>Add New Macro</Button>
</View>
);
}
}
According to your code, you need to pass your toggleModal function to TouchableOpacity in order to display your Model. Check below sample for more information.
import React, { Component } from 'react';
import { SafeAreaView, View, FlatList, StyleSheet, Text, TouchableOpacity, Modal, Button } from 'react-native';
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
];
export default class App extends Component {
state = {
isModalVisible: false
}
toggleModal = () => {
this.setState({
isModalVisible: !this.state.isModalVisible
});
};
renderItem = ({ item }) => (
<TouchableOpacity style={styles.item} onPress={this.toggleModal}>
<Text style={styles.title}>{item.title}</Text>
</TouchableOpacity>
)
render() {
return (
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={this.renderItem}
keyExtractor={item => item.id}
/>
{
this.state.isModalVisible &&
<Modal
visible={this.state.isModalVisible}
transparent={true}
animationType='slide'
onRequestClose={this.toggleModal}
>
<View style={styles.modelStyle}>
<View style={styles.modelWrapperStyle}>
<Text>Test</Text>
<Button title="Cancel" onPress={this.toggleModal} />
</View>
</View>
</Modal>
}
</SafeAreaView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 50,
},
item: {
backgroundColor: '#f9c2ff',
padding: 20,
marginVertical: 8,
marginHorizontal: 16,
},
title: {
fontSize: 32,
},
modelStyle: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: 'rgba(0, 0, 0, 0.5)'
},
modelWrapperStyle: {
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
padding: 20,
width: '90%'
}
});
Change this according to your requirement.
Hope this helps you. Feel free for doubts.
Hi how can I access the state where I'm fetching all the data in an other component ? I have a component Accueil where I'm fetching the data and a component UserItem where I'm styling and showing the info. So I'm in my Accueil component I have a flatlist and inside this flatlist in the renderItem function I'm passing the . So how can I access the state dataSource in UserItem ?
class UserItem extends React.Component {
render() {
const user = this.props.user;
const displayDetailForUser = this.props.displayDetailForUser;
var colorConnected;
if (user.Statut == "ON") {
colorConnected = "#1fbc26";
}
else if (user.Statut == "OFF") {
colorConnected = "#ff0303";
}
else {
colorConnected = "#ffd200";
}
return (
<TouchableOpacity style={styles.view_container} onPress={() =>
displayDetailForUser(user.MembreId, user.Pseudo, user.Photo, user.Age, user.Genre, user.Description, user.distance, user.Statut, user.localisation, user.principale )}>
<ImageBackground source={{ uri : user.Photo}} style={{ flex: 1, aspectRatio: 1, position: 'relative', borderColor: '#d6d6d6', borderWidth: 1}}>
<View style={[styles.bulle_presence, { backgroundColor: colorConnected } ]}></View>
<TouchableOpacity>
<Image style = {{aspectRatio:0.6, position:'absolute', resizeMode:'contain', height:40, width:40, right:15, top:15 }} source = {require("../Images/chat-bg.png")}/>
</TouchableOpacity>
</ImageBackground>
<View style={{ backgroundColor: '#d6d6d6', padding: 6 }}>
<View style={{ flexDirection: 'row', alignItems: 'center' }}>
<View>
<Text style={{ fontSize: 25 }}>{user.Age}</Text>
</View>
<View style={{ marginRight: 7, marginLeft: 7, backgroundColor: '#000000', width: 1, height: 26 }}></View>
<View style={{ flexDirection: 'column', flex:1 }}>
<Text style={{ fontSize: 13, fontWeight: '600' }}>{user.Pseudo}</Text>
<View style={{ flexDirection: 'row', justifyContent: 'space-between'}}>
<Text style={{ fontSize: 12 }}>{user.distance}</Text>
<Text style={{ fontSize: 12 }}>{user.Genre}</Text>
</View>
</View>
</View>
</View>
</TouchableOpacity>
)
}
}
I've tried with const user = this.props.dataSource but it's not working. Thanks
Edit:
lass Accueil extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: false,
refreshing: false,
location: null,
latitude:null,
longitude:null,
dataSource:[]
}
this.displayPosition = this.displayPosition.bind(this);
}
handleRefresh = () => {
this.setState (
{
refreshing: true,
},
() => {
setTimeout(() => {this.setState({refreshing: false,})}, 1000)
}
);
};
componentDidMount() {
const url = "SomeUrl";
fetch(url)
.then(res => res.json())
.then(res => {
this.setState({
dataSource: res
});
})
.catch(error => {
console.log("get data error:" + error);
});
}
static navigationOptions = ({ navigation }) => {
return {
headerRight: () => (
<View style={{marginLeft: 8, marginRight: 8, flexDirection: 'row', alignItems: 'center' }}>
<TouchableOpacity style={{ marginRight: 10 }} onPress={ () =>{ }}>
<Image style={{ width: 22, height: 22 }} source={require("../Images/search.png")} />
</TouchableOpacity>
<TouchableOpacity style={{marginLeft: 10, marginRight: 10 }} onPress={ () =>{{this.displayPosition()}}}>
<Image style={{ width: 22, height: 22 }} source={require("../Images/localisation.png")} />
</TouchableOpacity>
<TouchableOpacity style={{marginLeft: 10 }} onPress={ () =>{ }}>
<Image style={{ width: 22, height: 22 }} source={require("../Images/refresh.png")} />
</TouchableOpacity>
</View>
),
};
};
displayPosition = () => {
Geolocation.getCurrentPosition(
(position) => {
this.setState({
latitude: JSON.stringify(position.coords.latitude),
longitude: JSON.stringify(position.coords.longitude),
error: null,
});
console.log(this.state.latitude)
},
(error) => this.setState({ error: error.message }),
{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
);
}
_displayDetailForUser = (idUser, name, photo, age, pratique, description, distance, Statut, localisation, principale ) => {
//console.log("Display user with id " + idUser);
this.props.navigation.navigate("UserProfil", { idUser: idUser, name:name, photo: photo, age:age, pratique:pratique, description:description, distance:distance, Statut:Statut, localisation:localisation, principale:principale });
}
render() {
return (
<SafeAreaView style={{ flex:1 }}>
<View style={styles.main_container}>
<FlatList style={styles.flatList}
data={this.state.dataSource}
keyExtractor={(item) => item.MembreId}
renderItem={() => <UserItem user={this.state.dataSource} displayDetailForUser={this._displayDetailForUser} />}
numColumns={numColumns}
refreshing={this.state.refreshing}
onRefresh={this.handleRefresh} />
</View>
</SafeAreaView>
)
}
}
I am new to react-native
In reducer I set the initial value of the state.
while receiving the value in mapstate to props, it gives me the error
Type error : cannot read property of datasource.
I tried to set initial state to blank object then on fetch I set the value but I am still getting the error.
/* This is Dashboard.js */
import React, { Component } from 'react'
import { FlatList, StyleSheet, View, Text,Image,ActivityIndicator,
Picker,TouchableOpacity,SectionList,DrawerLayoutAndroid,Alert,
TouchableHighlight,Button} from 'react-native'
import NumericInput from 'react-native-numeric-input'
import {connect} from 'react-redux';
import {
createDrawerNavigator,
createStackNavigator,
createAppContainer,
} from 'react-navigation';
const mapStateToProps = (state) =>{
console.log(state)
return {
datasource:state.datasource,
isLoading:state.isLoading,
switchValue: state.switchValue,
page:state.page,
rerender:state.rerender,
isFetching: state.isFetching,
search:state.search,
LastSelectedItem:state.LastSelectedItem,
ItemSelected:state.ItemSelected,
setdrawerstate:state.setdrawerstate
}
};
const mapDispatchToProps=(dispatch)=>{
console.log('i am ni map dispatch to props')
return {
quantitychange:(prodindex, changevalue)=>dispatch({type:"CHANGE_QTY",
index:prodindex,
value:changevalue}),
selectvaluechange:(index,itemvalue,itemindex)=>dispatch({type:"CHANGE_WEIGHT",
index:index,
itemvalue:itemvalue,
itemindex:itemindex}),
ToogleDrawerState:(newState)=>dispatch({type:'TOOGLE_DRAWER',newState:newState}),
taggleSwitch:(value,ind)=>dispatch({type:'TOOGLE_SWITCH',value:value,ind:ind}),
fetchAllData:(AlldataJson)=>dispatch({type:'ALL_DATA',AlldataJson:AlldataJson})
};
};
class DashBoard extends Component {
constructor(props) {
super(props)
console.log('i am in constructor')
console.log('the value getting as props is '+JSON.stringify(props));
// this.selectvaluechange=this.selectvaluechange.bind(this);
// this._opendrawer = this._opendrawer.bind(this);
} //constructor
packageList = (index) =>{
// console.log('i am in package list'+index)
return( this.props.datasource[index].pack.map( (x,j) => {
return( <Picker.Item label={x.Weight} key={j} value={x.packId}/>)}));
}
// Verdana 20
renderItem = ({ item,index }) => {
// console.log('i am in render item index is '+index+' item vale is '+JSON.stringify(item));
return(
<View style={{
flex: 1, flexDirection: 'row', marginBottom: 3,
paddingBottom: 10, paddingTop:10, paddingLeft: 10, backgroundColor: 'white', height: '25%'
}}>
<View style={{ width: '30%' }}>
<Image style={{ resizeMode: 'contain', height: '100%',width:'100%' }}
source={{ uri: this.props.datasource[index].imageUrl }} />
</View>
<View style={{ alignContent: 'center', paddingLeft: 40, width: '65%' }}>
<Text style={{
fontSize: 20, color: 'black', fontWeight: 'bold',
fontFamily: 'Verdana'
}}>
{item.Heading}</Text>
<Text style={{
fontSize: 12, paddingTop: 10, fontFamily: 'Verdana',
color: 'black', fontWeight: 'bold'
}}>{item.Details}</Text>
<View style={{ flex: 1, flexDirection: 'row', paddingTop: 15 }}>
<Text style={{ width: 40, height: 30, fontFamily: 'Verdana', fontWeight: 'bold' }}>Qty :</Text>
<NumericInput
totalHeight={30}
totalWidth={80}
minValue={0}
value={this.props.datasource[index].Qty}
onChange={(value) => this.props.quantitychange(index, value)} />
<Picker
style={{ marginLeft: 10, width: '45%', height: 40, fontFamily: 'Verdana', fontWeight: 'bold' }}
mode="dropdown"
selectedValue={this.props.datasource[index].packselectedValue}
onValueChange={(itemValue, itemIndex) => this.props.selectvaluechange(index, itemValue, itemIndex)}>
{this.packageList(index)}
</Picker>
</View>
<View >
<Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }}>Price : {this.props.datasource[index].
pack[this.props.datasource[index].packselectedValue].Price}
<Text style={{ fontFamily: 'Verdana', fontWeight: 'bold' }}> Amount : {this.props.datasource[index].
pack[this.pack.datasource[index].packselectedValue].Price *
this.props.datasource[index].Qty}
</Text>
</Text>
</View>
</View>
</View>
)
}
renderSeperator=()=>{
console.log('I am renderseperator the data ')
return(
<View style={{height:1,width:'100%',backgroundColor:'black'}}/>
)
}
onRefresh=()=>{
console.log('I am refreshing the data '+this.props)
// this.setState({isFetching:false})
}
componentDidMount() {
AlldataJson = [{}];
console.log('i am in component didmount ');
const url='./../Data/AllProduct.json'
// ./../Data/AllProduct.json'
fetch(url)
.then((response) => response.json())
.then((responsejson => {
console.log('i am in response json')
fetchAllData(responsejson)}))
//this.setState({ datasource: responsejson })})
.catch((error) => {
console.log('error in fetching the data bhasker')
this.props.fetchAllData(AlldataJson);
console.log('i am after fetchalldata function'+this.props)
})
this.props.navigation.setParams({ opendrawer: this._opendrawer});
}
// data={this.state.page===1?this.state.datasource:[this.state.datasource]}
render() {
return (
this.props.isLoading ?
<View style={{ flex: 1, justifyContent: 'center', alignContent: 'center' }}>
<ActivityIndicator size='large' color='#330066' animating />
</View> : <View>
{/* <Text>{this.props.datasource[0].Heading}</Text> */}
<FlatList
extraData={this.props.state}
data={this.props.datasource}
onRefresh={() => this.onRefresh()}
refreshing={this.props.isFetching}
renderItem={(item,index)=>this.renderItem(item,index)}
keyExtractor={(item, index) => {
console.log('i am in keyextractor')
return (item.Id)}}
ItemSeparatorComponent={this.renderSeperator}/>
</View>
)
}
}
export default connect(mapStateToProps,mapDispatchToProps)(DashBoard);
/* My Reducer code is */
import * as types from '../Action/ActionType'
import { objectExpression } from '#babel/types';
import Allproduct from './../Data/AllProduct';
const initialstate={
datasource: Allproduct,
isLoading:false,
switchValue: true,
page:1,
rerender:true ,
isFetching: false,
search:"" ,
LastSelectedItem:{Item:"",qty:"",weight:""},
ItemSelected:0,
setdrawerstate:true
}
const reducer = (state = initialstate, action) => {
console.log('i am in reducer '+JSON.stringify(action));
switch (action.type) {
case "CHANGE_QTY":
break;
case "CHANGE_WEIGHT":
break;
case "TOOGLE_DRAWER":
break;
case "TOOGLE_SWITCH":
break;
case "ALL_DATA":
console.log('i am in all data') ;
return state;
default:
return state;
}
}
export default reducer;
/* if i comment datasource in mapstatetoprops it print the text value.
Allproduct json is below
*/
[{"Id":"1","Heading":"Ashirvad","Details": "ashirvad Atta - Whole Wheet 10k Pouch","imageUrl": "https://www.aashirvaad.com/images/packet-2-right.png", "Qty": 0,"pack": [{"packId":0,"Weight": "1kg","Price": 25}, {"packId":1,"Weight": "2kg","Price": 50}, {"packId":2,"Weight": "5kg","Price": 125}, {"packId":3,"Weight": "10kg","Price": 250}], "packselectedValue":0,"isselected": false,"categoryID":"1"}, {"Id":"2","Heading": "Tata Salt","Details": "Tata Salt Iodised Salt 1kg Product","imageUrl": "http://tatasalt.com/public/front_assets/images/tab-product-img1.png","Qty": 0,"pack": [{"packId":0,"Weight": "1kg","Price": 9.5},{"packId":1,"Weight": "2kg","Price": 19}, {"packId":2,"Weight": "5kg","Price": 47 },{"packId":3,"Weight": "10kg","Price": 92}],"packselectedValue":0,"isselected": false,"categoryID":"1"},
I don't understand the error message from the snack. "failed to install module ./assets/locales/sv.json..."
What does it mean? It seems to be this row that is failing:
// Import all locales
import en from './assets/locales/en.json';
import sv from './assets/locales/sv.json';
import he from './assets/locales/he.json';
import ar from './assets/locales/ar.json';
https://snack.expo.io/#niklasro/livejobb-snack
import React from 'react';
import { setLocale, strings, isoLangs } from './i18n.js';
import {Image, Picker, StyleSheet, ListView, Text, TextInput, TouchableHighlight, View} from 'react-native';
import {StackNavigator} from 'react-navigation'; // Version can be specified in package.json
import {Constants} from 'expo';
class HomeScreen extends React.Component {
state = {
language : '', itemValues: [], languages2: [], pickers: [], user: '',
username: 'Ivanka',
};
render() {
return (
<View style={styles.container}>
<View style={styles.section1}>
<Text style={[styles.text, {paddingBottom: 20}]}>{strings('login.welcome', { name: this.state.username })}</Text>
</View>
<View style={styles.section2}>
<Text style={[styles.text, {paddingTop: 20}]}>{strings('login.verified')}</Text>
</View>
<View style={styles.section3}>
<Text style={styles.text}>{strings('login.signup_as')}</Text>
</View>
<View style={styles.section4}>
<View style={styles.buttonContainer}>
<View style={styles.button}>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Details')}>
<Image source={require('./assets/stck2.png')} style={styles.image}/>
</TouchableHighlight>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Details')}>
<Text style={styles.buttonText}>{strings('login.translator')}</Text>
</TouchableHighlight>
</View>
<View style={styles.button}>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Recruiter')}>
<Image source={require('./assets/stck1.png')} style={styles.image}/>
</TouchableHighlight>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Recruiter')}>
<Text style={styles.buttonText}>{strings('login.recruiter')}</Text>
</TouchableHighlight>
</View>
</View>
<TouchableHighlight onPress={() =>{ setLocale('en'); this.setState({
dumme: 'dummy'
}); }}>
<Text style={styles.buttonText}>en</Text>
</TouchableHighlight>
<TouchableHighlight onPress={() => setLocale('sv')}>
<Text style={styles.buttonText}>sv</Text>
</TouchableHighlight>
</View>
</View>
);
}
}
class DetailsScreen extends React.Component {
constructor(props) {
super(props);
this.addLanguage = this.addLanguage.bind(this)
}
state = {
count: 0, itemValues: [], languages : [],languages2 : [], pickers: [], user: '',
username: 'Ivanka',
someVal: 'ar',
};
addLanguage() {
let pickers = this.state.pickers;
let count = this.state.count;
count++;
pickers.push(
{
id: 1,
color: "blue",
text: "text1"
}
);
let languages = this.state.languages;
languages.push('new');
this.setState({
count: count,
languages: languages,
});
let languages2 = this.state.languages2;
languages2.push('new');
this.setState({
count: count,
languages2: languages2,
});
}
update2(lang, ran, counter){
let languages2 = this.state.languages2;
languages2[counter]=lang;
this.setState({
languages2: languages2,
});
}
update(lang, ran, counter){
let languages = this.state.languages;
languages[counter]=lang;
this.setState({
languages: languages,
});
}
render() {
let counter = 0;
return (
<View style={{flex: 1, justifyContent: 'center', backgroundColor: '#fff'}}>
<View style={{flexDirection: 'row', justifyContent: 'center'}}>
<Text style={{
fontSize: 20,
fontFamily: 'normal',
color: 'skyblue',
}}>
{strings('login.whichlanguages')} {'\n'}
</Text>
</View>
{this.state.pickers.map((picker) => {
counter++;
console.log("p"+picker.toString());
return <View key={Math.random()} style={{flexDirection: 'row', justifyContent: 'center'}}>
<Picker style={{width: 150}} selectedValue={this.state.languages[counter-1]}
onValueChange={(lang) => this.update(lang, 0, counter-1)}
>
{
Object.keys(isoLangs).map((lang) => {
return <Picker.Item color="skyblue" key={Math.random()} label={isoLangs[lang].name} value={lang}/>
})
}
</Picker>
<Image
source={require('./assets/Arrow.png')}
/>
<Picker style={{width: 150}} selectedValue={this.state.languages2[counter-1]}
onValueChange={(lang) => this.update2(lang, 0, counter-1)}
>
{
Object.keys(isoLangs).map((lang) => {
return <Picker.Item color="skyblue" key={Math.random()} label={isoLangs[lang].name} value={lang}/>
})
}
</Picker>
</View>
})}
<View style={{flexDirection: 'row', justifyContent: 'center'}}>
<TouchableHighlight onPress={() => this.addLanguage()}>
<Text style={{
fontSize: 25,
fontFamily: 'normal',
alignItems: 'center',
color: 'skyblue',
}}>{'\n'}+ {strings('login.addlanguage')}{'\n'}{'\n'}</Text>
</TouchableHighlight>
</View>
<View style={{flexDirection: 'row', justifyContent: 'center'}}>
<TouchableHighlight onPress={() => this.props.navigation.navigate('Screen3')}>
<Image
source={require('./assets/Next.png')}
/>
</TouchableHighlight>
</View>
</View>
);
}
}
const adresses = [
{
street: "English",
city: "Sydney",
country: "Australia"
},{
street: "Estonian",
city: "Sydney",
country: "Australia"
},{
street: "Esperanto",
city: "Sydney",
country: "Australia"
}
];
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
class AutoComplete extends React.Component {
constructor(props) {
super(props);
this.state = {
searchedAdresses: []
};
}
submit() {
}
searchedAdresses = (searchedText) => {
let searchedAdresses = adresses.filter(function(adress) {
return adress.street.toLowerCase().indexOf(searchedText.toLowerCase()) > -1;
});
this.setState({searchedAdresses: searchedAdresses});
};
renderAdress = (adress) => {
return (
<TouchableHighlight onPress={() => this.submit()}>
<View>
<Text>{adress.street}</Text>
</View>
</TouchableHighlight>
);
};
render() {
return (
<View style={styles.row}>
<View style={styles.container2}>
<TextInput
style={styles.textinput}
onChangeText={this.searchedAdresses}
placeholder="Type your language here" />
<ListView
dataSource={ds.cloneWithRows(this.state.searchedAdresses)}
renderRow={this.renderAdress} />
</View>
<View style={styles.container2}>
<TextInput
style={styles.textinput}
onChangeText={this.searchedAdresses}
placeholder="Type your language here" />
<ListView
dataSource={ds.cloneWithRows(this.state.searchedAdresses)}
renderRow={this.renderAdress} />
</View>
</View>
);
}
}
const RootStack = StackNavigator(
{
Home: {
screen: HomeScreen,
},
Details: {
screen: DetailsScreen,
},
AutoComplete: {
screen: AutoComplete,
},
},
{
initialRouteName: 'Home',
}
);
export default class App extends React.Component {
render() {
return <RootStack/>;
}
}
const styles = StyleSheet.create({
row: {
flex: 1,
flexDirection: "row"
},
container2: {
flex: 0.5,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF',
},
textinput: {
marginTop: 30,
backgroundColor: '#DDDDDD',
height: 40,
width: 150
},
container: {
flex: 1,
paddingTop: Constants.statusBarHeight,
backgroundColor: '#fff',
},
section1: {
flex: 0.17,
justifyContent: 'flex-end',
alignItems: 'center'
},
section2: {
flex: 0.30,
justifyContent: 'flex-start',
alignItems: 'center'
},
section3: {
flex: 0.10,
justifyContent: 'center',
alignItems: 'center'
},
section4: {
flex: 0.43
},
text: {
fontSize: 24,
color: '#53a6db',
textAlign: 'center',
paddingTop: 40,
paddingBottom: 40,
paddingLeft: 40,
paddingRight: 40
},
buttonContainer: {
flex: 1,
flexDirection: 'row'
},
button: {
flex: 0.5,
justifyContent: 'center',
alignItems: 'center'
},
buttonText: {
fontSize: 24,
color: '#53a6db',
textAlign: 'center',
paddingTop: 5,
paddingBottom: 5,
paddingLeft: 5,
paddingRight: 5
},
image: {
width: 100,
height: 100
}
});
Comments can't be used in JSON
You have syntax errors in your .json files by using a comment. Fixed snack.