I'm trying to update listview from a function, But currently it is not updating, Here is the complete source code.
Please also mention that what I am doing wrong
import React, { Component } from 'react';
import {
AppRegistry,
ListView,
TextView,
Text,
View
} from 'react-native';
const ds = new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 != row2 });
var myarray = [];
export default class filesix extends Component {
constructor() {
super();
this.state = {
dataSource: ds.cloneWithRows(myarray),
};
console.log(`ds const =${myarray}`);
}
componentDidMount() {
myarray = ['11', '22'];
console.log(myarray);
this.setState = ({
datasource: this.state.dataSource.cloneWithRows(myarray),
});
this.prepareDataSource();
console.log('this componentDidMount');
}
prepareDataSource() {
myarray = ['11', '22'];
console.log(myarray);
}
renderRow(rowData) {
return <Text>{JSON.stringify(rowData)}</Text>
}
render() {
return (
<View style={{ flex: 1, borderWidth: 2 }}>
<ListView
enableEmptySections={true}
dataSource={this.state.dataSource}
renderRow={this.renderRow}
/>
</View>
);
}
}
AppRegistry.registerComponent('filesix', () => filesix);
I already spent my whole day to update the values, but no luck, Please correct my understanding.
Your componentDidMount has a typo. It's setting state on datasource but your ListView is using dataSource.
Related
I copied fallowing code from a github project and tried using expo. The project executed without error but when i press button nothing happens. not even error this is my code
NB- I stetted an alert inside onChooseImagePress and alert is working fine
import React from 'react';
import { Image, StyleSheet, Button, Text, View, Alert, } from 'react-native';
import { ImagePicker } from 'expo';
import * as firebase from 'firebase';
import {firebaseConfig} from "./ApiKeys";
export default class HomeScreen extends React.Component {
static navigationOptions = {
header: null,
};
onChooseImagePress = async () => {
let result = await ImagePicker.launchCameraAsync();
//let result = await ImagePicker.launchImageLibraryAsync();
if (!result.cancelled) {
this.uploadImage(result.uri, "test-image")
.then(() => {
Alert.alert("Success");
})
.catch((error) => {
Alert.alert(error);
});
}
}
uploadImage = async (uri, imageName) => {
const response = await fetch(uri);
const blob = await response.blob();
var ref = firebase.storage().ref().child("images/" + imageName);
return ref.put(blob);
}
render() {
return (
<View style={styles.container}>
<Button title="Choose image..." onPress={this.onChooseImagePress} />
</View>
);
}
}
const styles = StyleSheet.create({
container: { flex: 1, paddingTop: 50, alignItems: "center", },
});
}
Multiple syntactical issues in your code:
const styles... should be defined inside the render function currently its dangling outside the class
Brackets mismatch
return (
<View style={styles.container}>
<Button title="Choose image..." onPress={this.onChooseImagePress} />
</View>
);
}
} // the class ends here
Please let me know if it still doesn't work
Try to use below code
constructor() {
super();
this.state = { };
this.onChooseImagePress= this.onChooseImagePress.bind(this);
}
<Button title="Choose image..." onPress={() => this.onChooseImagePress()} />
I have an app that reads a JSON file. In one tab I have it coming out as a list, on another tab, I want it to show the items selected from the file as the labels for a radio button I found here:
https://www.npmjs.com/package/react-native-radio-buttons-group
Here's the code that I have for the tab of my app that pulls names of medications from a JSON file:
import React, { Component } from "react";
import {
View,
Text,
StyleSheet,
TouchableHighlight,
FlatList
} from "react-native";
import { Icon } from 'native-base'
import RadioGroup from 'react-native-radio-buttons-group';
//import MultipleChoice from 'react-native-multiple-choice'
class LikesTab extends Component {
_onSelect = ( item ) => {
console.log(item);
};
onPress = data => this.setState({ data });
constructor(props){
super(props);
this.state = {
data:[]
}
}
//SETTING THE STATE MAKING AN EMPTY ARRAY WHICH WE FIL
// state = {
// data: []
//};
componentWillMount() {
this.fetchData();
}
//Getting the data
fetchData = async () => {
const response = await fetch("https://api.myjson.com/bins/s5iii");
const json = await response.json();
this.setState({ data: json.results });
};
//var customData = require('./customData.json');
//Setting what is shown
render() {
return (
<View style={{ marginVertical: 10, backgroundColor: "#E7E7E7" }} >
<FlatList
data={this.state.data}
keyExtractor={(x, i) => i}
renderItem={({ item }) =>
<Text>
{`${item.name.first} ${item.name.last}`}
</Text>}
/>
</View>
);
}
}
export default LikesTab;
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center'
}
});
Here's my tab for the radio button
import React, { Component } from 'react';
import { Text, View, StyleSheet } from 'react-native';
import RadioGroup from 'react-native-radio-buttons-group';
export default class AddMediaTab extends Component {
componentWillMount() {
this.fetchData();
}
//Getting the data
fetchData = async () => {
const response = await fetch("https://api.myjson.com/bins/s5iii");
const json = await response.json();
this.setState({ data: json.results });
};
state = {
data: [
{
label:' ' ,
}
]
};
// update state
onPress = data => this.setState({ data });
render() {
let selectedButton = this.state.data.find(e => e.selected == true);
selectedButton = selectedButton ? selectedButton.value : this.state.data[0].label;
return (
<View style={styles.container}>
<Text style={styles.valueText}>
Value = {selectedButton}
</Text>
<RadioGroup radioButtons={this.state.data} onPress={this.onPress}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
valueText: {
fontSize: 18,
marginBottom: 50,
},
});
What is your selectedButton variable? I think Value = {selectedButton} is the issue. If selectedButton evaluates to a string, fine but it looks like it is an object in your case. Array.find() returns the first element that satisfies the condition, or if none satisfy it it returns undefined. If that variable undefined during the time it's waiting for your api call to return something that could cause an issue as well.
I'm making a list view were I will view a list of some data from my database. But after running the program all I got is white background screen. Does anyone knows the solution?
screen shot
Here is my code
export default class Pasta extends Component {
constructor() {
super()
this.state = {
dataSource: []
}
}
renderItem = ({ item }) => {
return (
<View style = {{flex: 1, flexDirection: 'row'}}>
<View style = {{flex: 1, justifyContent: 'center'}}>
<Text>
{item.menu_desc}
</Text>
<Text>
{item.menu_price}
</Text>
</View>
</View>
)
}
componentDidMount() {
const url = 'http://192.***.***.***:9090/menu'
fetch(url)
.then((response) => response.json())
.then((responseJson) => {
this.setState({
dataSource: responseJson.menu
})
})
}
render() {
return (
<View style = { styles.container }>
<FlatList
data = { this.state.dataSource }
renderItem = {this.renderItem}
/>
</View>
);
}
}
Add extraData prop to your FlatList to cause a re-render
keyExtractor = (item, index) => item.id; // note: id is the unique key for each item
render() {
return (
<FlatList
data = {this.state.dataSource}
renderItem = {this.renderItem}
extraData={this.state}
keyExtractor={this.keyExtractor}
/>
);
}
Also log and verify your data is present. I suggest referring to FlatList docs for more props like keyExtractor etc.
Hello fellow programmers, I am having this problem developing this React-Native app where i am rendering a ListView of 'Services' where in each row it has a Text and a Switch, and I am able to render it but when i tap on the row's switch to change the value it goest back to its initial value real fast, I was wondering how to keep this change of vale but since I am new into this I am pretty clueless of how this is done: so far I have the ListView component where I call my ListItem component, heres my code;
class ListView extends Component {
constructor(props) {
super(props);
this.state = {
servicios: []
};
}
componentDidMount() {
AsyncStorage.getItem("token").then((value) => {
axios.get('http://MYURL/api/servicio/index?token=' + value)
.then(response => this.setState({ servicios: response.data.servicios }))
.catch(function (error) {
console.log(error);
});
}).done();
}
renderList() {
console.log('here');
return this.state.servicios.map(servicio =>
<ListItem key={servicio.id} servicio={servicio} />);
}
render() {
const { navigation } = this.props.navigation;
return (
<ScrollView>
{this.renderList()}
</ScrollView>
);
}
}
ListItem.js
const ListItem = ({ servicio }) => {
const { nombre, created_at, estatus } = servicio;
const { thumbnailStyle, headerContentStyle, thumbnailContainerStyle, headerTextStyle, imageStyle } = styles;
return (
<Card>
<CardSection>
<View style={thumbnailContainerStyle}>
<Text style={headerTextStyle}>{nombre}</Text>
</View>
<View style={headerContentStyle}>
<Switch value={estatus}/>
</View>
</CardSection>
</Card>
);
export default ListItem;
I missed the styles to not make this post too long, I may have the clue that i've got to put the current's row switch status in the State but I dont know how to do it, I would be really glad if you guys could help me?
Thanks in advance.
In order to change value of the switch you need to change value in the state from which you're rendering the ListView. I haven't tested that and wrote that from the top of my head, but you should achieve it by introducing small changes here and there:
ListItem.js
const ListItem = ({ servicio, onToggleSwitch }) => {
const { nombre, created_at, estatus, id } = servicio;
const { thumbnailStyle, headerContentStyle, thumbnailContainerStyle, headerTextStyle, imageStyle } = styles;
return (
<Card>
<CardSection>
<View style={thumbnailContainerStyle}>
<Text style={headerTextStyle}>{nombre}</Text>
</View>
<View style={headerContentStyle}>
<Switch value={estatus} onValueChange={(value) => onToggleSwitch(id, value)} />
</View>
</CardSection>
</Card>
);
export default ListItem;
ListView.js
class ListView extends Component {
constructor(props) {
super(props);
this.state = {
servicios: []
};
}
onToggleSwitch = (id, value) => {
const servicios = [...this.state.servicios]
const index = servicios.findIndex(item => item.id === id)
servicios[index].estatus = value
this.setState({ servicios })
}
componentDidMount() {
AsyncStorage.getItem("token").then((value) => {
axios.get('http://MYURL/api/servicio/index?token=' + value)
.then(response => this.setState({ servicios: response.data.servicios }))
.catch(function (error) {
console.log(error);
});
}).done();
}
renderList() {
console.log('here');
return this.state.servicios.map(servicio =>
<ListItem key={servicio.id} servicio={servicio} onToggleSwitch={this.onToggleSwitch} />);
}
render() {
const { navigation } = this.props.navigation;
return (
<ScrollView>
{this.renderList()}
</ScrollView>
);
}
}
I have been wanting to make search filter in this listitem but i kind of get confused, if you are experienced with this, please take a look at my code.
import React, { Component } from 'react';
import { Text, View, ScrollView, TextInput, } from 'react-native';
import { List, ListItem } from 'react-native-elements';
import { users } from '../config/data';
class Feed extends Component { constructor(props){
super(props);
this.state = {
user:'',
} } onLearnMore = (user) => {
this.props.navigation.navigate('Details', { ...user }); };
filterSearch(text){
const newData = users.filter((item)=>{
const itemData = item.name.first.toUpperCase()
const textData = text.toUpperCase()
return itemData.indexOf(textData)>-1
})
this.setState({
text:text
}) }
render() {
return (
<ScrollView>
<TextInput
onChangeText={(text) => this.filterSearch(text)}
value={this.state.text}
/>
<List>
{users.map((user) => (
<ListItem
key={user.login.username}
roundAvatar
avatar={{ uri: user.picture.thumbnail }}
title={`${user.name.first.toUpperCase()} ${user.name.last.toUpperCase()}`}
subtitle={user.email}
onPress={() => this.onLearnMore(user)}
/>
))}
</List>
</ScrollView>
); } }
export default Feed;
i have been surfing the internet but i found that most of it discuss about listview instead of list item from react-native-elements, help me!
You were almost correct. You successfully filter your users but then render the same not filtered users in your list. To change this easily you can use component state.
Example
import React, { Component } from 'react';
import { Text, View, ScrollView, TextInput, } from 'react-native';
import { List, ListItem } from 'react-native-elements';
import { users } from '../config/data';
class Feed extends Component {
constructor(props){
super(props);
this.state = {
user:'',
users: users // we are setting the initial state with the data you import
}
}
onLearnMore = (user) => {
this.props.navigation.navigate('Details', { ...user });
};
filterSearch(text){
const newData = users.filter((item)=>{
const itemData = item.name.first.toUpperCase()
const textData = text.toUpperCase()
return itemData.indexOf(textData)>-1
});
this.setState({
text:text,
users: newData // after filter we are setting users to new array
});
}
render() {
// rather than mapping users loaded from data file we are using state value
return (
<ScrollView>
<TextInput
onChangeText={(text) => this.filterSearch(text)}
value={this.state.text}
/>
<List>
{this.state.users.map((user) => (
<ListItem
key={user.login.username}
roundAvatar
avatar={{ uri: user.picture.thumbnail }}
title={`${user.name.first.toUpperCase()} ${user.name.last.toUpperCase()}`}
subtitle={user.email}
onPress={() => this.onLearnMore(user)}
/>
))}
</List>
</ScrollView>
); } }
export default Feed;
why do i keep answering my own answer
i am so sorry to this forum that i waste some space
but i thought posting this answer will help some of you especially a beginner like me
import React, {Component} from 'react';
import { StyleSheet, Text, View, ListView, TouchableHighlight, TextInput} from 'react-native';
import { List, ListItem } from 'react-native-elements';
import { users } from '../config/data';
export default class Feed extends Component {
constructor(props){
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1,r2) => r1 !== r2})
this.state = {
dataSource: ds.cloneWithRows(users),
text:'',
}
}
onLearnMore = (rowData) => {
this.props.navigation.navigate('Details', { ...rowData });
};
renderRow(rowData){
return(
<ListItem
key={rowData.login.username}
roundAvatar
avatar={{ uri: rowData.picture.thumbnail }}
title={`${rowData.name.first.toUpperCase()} ${rowData.name.last.toUpperCase()}`}
subtitle={rowData.email}
onPress={() => this.onLearnMore(rowData)}
/>
);
}
filterSearch(text){
const newData = users.filter(function(item){
const itemData = item.email.toUpperCase()
const textData = text.toUpperCase()
return itemData.indexOf(textData) > -1
})
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newData),
text: text
})
}
render() {
return (
<View style={{flex:1}}>
<TextInput
onChangeText={(text) => this.filterSearch(text)}
value={this.state.text}
/>
<ListView
enableEmptySections={true}
style={{marginHorizontal:10}}
renderRow={this.renderRow.bind(this)}
dataSource={this.state.dataSource}
/>
</View>
);
}
}
just compare the question's code and the answer code
and lastly i get the answer by reading the link below
https://react-native-training.github.io/react-native-elements/API/lists/
feel free to check it out again