React-native can't display images from database - react-native

I can't display images in my react-native application. I have a simple database connected with php for my application where I added the images path, they are stored locally. All I am trying to do is to retrieve the strings for the location. If I write the path manually it works.
Here is the code for the component
export default class Accordian extends Component{
constructor(props) {
super(props);
this.state = {
data: props,
expanded : false,
updated_Height: 0,
}
if (Platform.OS === 'android') {
UIManager.setLayoutAnimationEnabledExperimental(true);
}
}
componentWillReceiveProps(update_Props) {
if (update_Props.item.expanded) {
this.setState(() => {
return {
updated_Height: null
}
});
}
else {
this.setState(() => {
return {
updated_Height: 0
}
});
}
}
shouldComponentUpdate(update_Props, nextState) {
if (update_Props.item.expanded !== this.props.item.expanded) {
return true;
}
return false;
}
render() {
return (
<View style={styles.Panel_Holder}>
<TouchableOpacity activeOpacity={0.7} onPress={this.props.onClickFunction} style={styles.Btn}>
<Text style={styles.Panel_Button_Text}>{this.props.item.make} {this.props.item.model}</Text>
<Text style={styles.Panel_Button_Text}>{this.props.item.price}$/day</Text>
</TouchableOpacity>
<View style={{ height: this.state.updated_Height, overflow: 'hidden' }}>
<View style={{width:400,flexDirection:"row", alignItems:"center", justifyContent:"space-evenly"}}>
<View style={{width:110,}}>
<Text style={{bottom:50, fontSize:25, fontWeight:"bold"}}>
{this.props.item.name}
</Text>
<Text>
<Image source={require('../images/person-silhouette.png')} />
{this.props.item.nr_seats}
</Text>
<Text>
<Image source={require('../images/shopping-bag.png')} />
{this.props.item.bag_capacity}
</Text>
<Text>
<Image source={require('../images/gas-station.png')} />
{this.props.item.gas_desc}
</Text>
{console.log( this.props.item.cars_img)}
</View>
<View style={{width:220,height:300,alignItems:"center",justifyContent:"center",}}>
<Image style={{ flex: 1, width: '100%', height: '1000%',resizeMode: 'contain',}} source={this.props.item.cars_img}/>
</View>
</View>
</View>
</View>
)
}
}

Try changing it to source={{uri: this.props.item.cars_img}}

Related

React native how to manage list of inputs

I wrote an api it return jsondata and limit. I'm creating inputlist in scrollview by lenght of limit.In creation i set the values to input comes from jsondata. Jsondata is may content 0-30 value.
I just gotta how to save this as array.
Here's my code it gives value to input if not undefined
Also do i need onchange for input component for input
export class DataListFor extends Component {
constructor() { super();
this.state = {
dataSource: [],
limit: 30,
}; }
componentDidMount() {
const url = "https://sssaaaaaexample.herokuapp.com/getExample";
this.setState({
dataSource: this.props.route.params.list,
limit: this.props.route.params.limit,
})
}
render() {
var itemList = [];
var data=this.state.dataSource;
for(let i = 0; i < this.state.limit; i++){
if(data[i]==undefined)
{
itemList.push(
<View key = {i}>
<View>
<TextInput
style={{ height: "auto",width:'auto', alignItems: 'center',
fontSize: 20,borderColor:'white',borderWidth:1}}
/>
</View>
</View>
)
}
else{
itemList.push(
<View key = {i}>
<View>
<TextInput
style={{ height: "auto",width:'auto',borderColor:'white',borderWidth:1}}
value={data[i].text}
/>
</View>
</View>
)
}
}
return (
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'space-between',
}}>
<View >
<Text style={appStyles.listHeader}> To-do</Text>
</View>
<ScrollView style={appStyles.scrollView}>
{ itemList }
</ScrollView>
<Button
title="Save"
onPress={() => console.log("saved")}
/>
</View>
)
}
}

Getting a warning when passing from one screen to another

The error doesn't keep me from going from one screen to another but I want to understand it.
The error is:
Warning: Cannot update during an existing state transition (such as within render). Render methods should be a pure function of props and state.
The first screen code is:
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isFirstConnection: true,
status: 0,
fontLoaded: false,
isConnected: false
};
}
async UNSAFE_componentWillMount() {
let lang = await retrieveAppLang();
if (lang.length == 2) {
i18n.changeLanguage(lang);
}
}
async componentDidMount() {
let isConnected = await userSessionActive();
await Font.loadAsync({
FunctionLH: require("./assets/fonts/FunctionLH-Light.ttf"),
});
const data = await this.performTimeConsumingTask();
if (data !== null && (isConnected === false || isConnected === true)) {
this.setState({
isFirstConnection: false,
status: 1,
fontLoaded: true,
isConnected: isConnected
});
}
}
performTimeConsumingTask = async () => {
return new Promise((resolve) =>
setTimeout(() => {
resolve("result");
}, 1500)
);
};
render() {
if (this.state.status == 1) {
if (this.state.isFirstConnection && this.state.fontLoaded) {
return <SplashScreen />;
} else if (this.state.isConnected === true) {
// TODO : Use Navigation !
return <Navigation screenProps={'MyTrips'}/>;
} else {
return <Navigation screenProps={'Authentication'}/>;
}
}
return (
<ImageBackground
source={require("./assets/images/background.jpg")}
style={{ flex: 1 }}
>
<View style={[styles2.container, styles2.containerCentered]}>
<StatusBar hidden={true} />
<View style={styles2.subContainer}>
<Image
style={styles2.logo}
source={require("./assets/images/logo.png")}
/>
<ActivityIndicator size="large" color="#43300E" />
<Text>Loading data...</Text>
</View>
</View>
</ImageBackground>
);;
}
}
The second screen (I guess this is the origin of the problem):
export default class MyTrips extends Component {
constructor(props) {
super(props);
this.state = {
location: null,
errorMessage: null,
measured: false,
height: 0,
value1: 0,
};
}
handleLayout = (e) => {
this.setState({
measured: true,
height: e.nativeEvent.layout.height + 1,
});
};
render() {
return (
<ImageBackground
source={require("../../assets/images/background.jpg")}
style={styles.backgroundImage}
>
<Header
backgroundImage={require("../../assets/images/bg-header.png")}
backgroundImageStyle={{
resizeMode: "stretch",
}}
centerComponent={{
text: i18n.t("mytrips.title"),
style: styles.headerComponentStyle,
}}
containerStyle={[styles.headerContainerStyle, { marginBottom: 0 }]}
statusBarProps={{ barStyle: "light-content" }}
/>
<ScrollView style={styles.containerScrollNoMargins}>
<View style={{ width: '100%', height: height / 3 + 40}}>
<WebView
geolocationEnabled={true}
source={{
uri:
"https:blabla",
}}
originWhitelist={[
"https://www.blabla.org",
"https://www.hophop.com",
]}
injectedJavaScript={`const meta = document.createElement('meta');
meta.setAttribute('content', 'width=device-width, initial-scale=0.5, maximum-
scale=0.5, user-scalable=0'); meta.setAttribute('name', 'viewport');
document.getElementsByTagName('head')[0].appendChild(meta); `}
scalesPageToFit={false}
style={{ marginHorizontal: 0, backgroundColor: "transparent" }}
/>
</View>
<View style={styles.container}>
<Text>{"\n"}</Text>
<TouchableOpacity
style={styles.touchable}
onPress={() => this.props.navigation.navigate("TripsForm")}
>
<View style={styles.view}>
<Text style={styles.textimg}>{i18n.t("mytrips.trip")}</Text>
</View>
<Image
source={require("../../assets/images/btn-background.png")}
style={styles.tripsimg}
/>
</TouchableOpacity>
</View>
<View style={styles.container}>
<Image
source={require("../../assets/images/cadran.png")}
style={styles.btnWithIcon}
/>
<View style={[styles.row, { marginTop: 28 }]}>
<Text style={styles.statText}>
{i18n.t("stats.action.dist")}
{"\n"}
<AnimateNumber
value={10000}
countBy={100}
style={{
fontFamily: "FunctionLH",
fontSize: 24,
color: "#FFF",
}}
/>
</Text>
</View>
<Text
style={[styles.textimg, styles.measure]}
onLayout={this.handleLayout}
>
0
</Text>
<Image
source={require("../../assets/images/btn-background.png")}
style={styles.cadran}
/>
</View>
<View style={styles.container}>
<Image
source={require("../../assets/images/hublo.png")}
style={styles.btnWithIcon}
/>
<View style={[styles.row, { marginTop: 28 }]}>
<Text style={styles.statText}>
{i18n.t("stats.action.flights")}
{"\n"}
<AnimateNumber
value={100}
countBy={1}
style={{
fontFamily: "FunctionLH",
fontSize: 24,
color: "#FFF",
}}
/>
</Text>
</View>
<Text
style={[styles.textimg, styles.measure]}
onLayout={this.handleLayout}
>
0
</Text>
<Image
source={require("../../assets/images/btn-background.png")}
style={styles.cadran}
/>
</View>
<Text>{"\n"}</Text>
</ScrollView>
</ImageBackground>
);
}
}
I found the solution but I don't really understand why there was an error...
Instead of:
return <Navigation screenProps={'MyTrips'}/>;
} else {
return <Navigation screenProps={'Authentication'}/>;
}
I directly imported the screens and this works:
return <MyTrips/>;
} else {
return <Authentication />;

componentWillReceiveProps not triggering from child screen inside Tabview

I'm new in React native here. I got stuck on this scenario. I have a Dashboard screen. Inside dashboard screen, there's Hitcher screen that has Tabview. And there are HitcherTrip and HitcherChat inside the Tabview. In HitcherTrip, i expected componentWillReceiveProps() will trigger after calling Actions.goToOtherLayout() but componentWillReceiveProps() is triggered on Dashboard screen (Parent screen).
Dashboard
const Menu = createDrawerNavigator(
{
First: { screen: Hitcher },
Second: { screen: Driver }
},
{
contentComponent: props => (
<ScrollView>
<View style={{ padding:20, backgroundColor:'#4ca858' }}>
<Image source={require('../assets/pp.png')} style={{ borderRadius: 40, borderWidth: 1, borderColor: '#fff',width:80, height: 80 }} />
<CustomDrawerText/>
</View>
<SafeAreaView forceInset={{ top: "always", horizontal: "never" }}>
<Drawer.Item
label="I am Hitcher"
style={styles.drawerItem}
onPress={
() => {}
}
/>
<View style={{ height:1, backgroundColor:'#a8a8a8', marginLeft: 15, marginRight: 15 }}/>
<Drawer.Item
label="I am Driver"
onPress={
() => {}
}
style={styles.drawerItem}
/>
<View style={{ height:1, backgroundColor:'#a8a8a8', marginLeft: 15, marginRight: 15 }}/>
<Drawer.Item
label="Settings"
style={styles.drawerItem}
/>
<View style={{ height:1, backgroundColor:'#a8a8a8', marginLeft: 15, marginRight: 15 }}/>
<Drawer.Item
label="Log Out"
style={styles.drawerItem}
onPress={
() => {}
}
/>
<View style={{ height:1, backgroundColor:'#a8a8a8', marginLeft: 15, marginRight: 15 }}/>
</SafeAreaView>
</ScrollView>
)
}
);
const AppNav = createAppContainer(Menu);
export default class Dashboard extends React.Component {
constructor(props) {
super(props)
}
componentWillReceiveProps(props) {
console.log("Dashboard");
}
render() {
return(
<AppNav />
)
}
}
Hitcher
export default class Hitcher extends React.Component {
state = {
index: 0,
routes: [
{ key: 'first', title: 'My Trips' },
{ key: 'second', title: 'Chats' },
],
};
async _storeItem(key, token) {
try {
var token = await AsyncStorage.setItem(key, token);
return token;
} catch (error) {
console.log(error.message);
}
}
render() {
return (
<View style={styles.container}>
<Appbar.Header
style={{ backgroundColor: '#4ca858' }}>
<Appbar.Action
icon="menu"
color="white"
onPress={() =>
this.props.navigation.dispatch(DrawerActions.toggleDrawer())
}
/>
<Appbar.Action icon={require('../assets/logo_inverted.png')} style={{flex:1, alignSelf:'center'}} size={65} color="white"/>
<Appbar.Action icon="bell" color="white"/>
</Appbar.Header>
<View style={styles.container}>
<TabView
style={{ marginTop: 10 }}
navigationState={this.state}
renderScene={SceneMap({
first: HitcherTrip,
second: HitcherChat,
})}
renderTabBar={props =>
<TabBar
{...props}
labelStyle={styles.label}
indicatorStyle={styles.indicator}
style={styles.tabbar}
getLabelText={({ route }) => route.title}
/>
}
onIndexChange={index => this.setState({ index })} />
</View>
</View>
);
}
}
HitcherTrip
export default class HitcherTrip extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
isFetching: false,
spinner: false,
itemId: 0
};
}
componentDidMount() {
this.getTrips();
}
getTrips = () => {
// codes
};
componentWillReceiveProps(props) {
console.log("HitcherTrip");
}
onRefresh() {
this.setState({isFetching: true,},() => {this.getTrips();});
}
createTrip = () => {
Actions.goToOtherLayout();
};
render() {
return(
<View style={styles.scene} >
<FlatList
showsVerticalScrollIndicator={false}
data={this.state.data}
renderItem={({item}) => {
var date = Moment(item.created_at).format('DD MMM');
var now = Moment();
var expired = Moment(item.expired_at);
var status = item.status_name;
if (now > expired && item.status == 0)
status = "Expired";
return (
<TouchableOpacity onPress={
() => {
}
}>
<Spinner
visible={this.state.spinner}
textContent={'Loading...'}
textStyle={styles.spinnerTextStyle}
/>
<View style={styles.container}>
{item.status == 0 ?
<View style={styles.header}>
<Text style={styles.headerLeftActive}>{status}</Text>
<Text style={styles.headerRightActive}>{item.request_no}</Text>
</View> :
<View style={styles.headerInActive}>
<Text style={styles.headerLeftInactive}>{status}</Text>
<Text style={styles.headerRightInactive}>{date}</Text>
</View>
}
<View style={styles.content}>
<Image source={require('../assets/fromto.png')} style={styles.image} />
<View style={styles.textContent}>
<Text style={styles.address}>{item.pickup_location}</Text>
<View style={{flex: 1}} />
<Text style={styles.address}>{item.dropoff_location}</Text>
</View>
</View>
</View>
</TouchableOpacity>
)}
}
keyExtractor={item => item.request_no}
onRefresh={() => this.onRefresh()}
refreshing={this.state.isFetching}
/>
<TouchableOpacity
style={{
alignItems:'center',
justifyContent:'center',
width:70,
position: 'absolute',
bottom: 10,
right: 10,
height:70,
backgroundColor:'#4ca858',
borderRadius:100,
elevation: 6,
}} onPress={this.createTrip}>
<Text style={{color:'#fff', fontSize: 32}}>+</Text>
</TouchableOpacity>
</View>
)
}
}
On other layout, i have set
Actions.pop(); setTimeout(()=> Actions.refresh(), 500);
to trigger componentWillReceiveProps() when press back button. But it only triggers on Dashboard screen.
How to trigger componentWillReceiveProps() on HitcherTrip? Or maybe trigger HitcherTrip function from Dashboard screen?

How to set state of different properties?

I am new to react native. i am using 'react-native-ratings' library for the star rating, and i have 3 places where i am using rating component but don't know how to set state of the property for each of the views.
Here is the code below, i want to update technicalRating, analyticalRating, commRating:
export class Feedback extends Component {
constructor(props) {
super(props);
this.state = {
technicalRating: '',
analyticalRating: '',
commRating:'',
}
}
render() {
return (
<View style={styles.row}>
<View style={styles.view}>
<Text style={styles.skillsText}>Technical Skills*</Text>
</View>
<RatingView />
</View>
<View style={styles.row}>
<View style={styles.view}>
<Text style={styles.skillsText}>Analytical Skills*</Text>
</View>
<RatingView />
</View>
<View style={styles.row}>
<View style={styles.view}>
<Text style={styles.skillsText}>Communication*</Text>
</View>
<RatingView />
</View>
}
}
export class RatingView extends Component {
ratingCompleted(rating) {
console.log("Rating is: " + rating)
}
render() {
return <Rating
showRating
onFinishRating={this.ratingCompleted}
style={{ marginRight: 10, marginTop: 6 }}
fractions={1}
imageSize={20}
showRating={false}
startingValue={0}
/>
}
}
Thanks in advance.
Try below code :
export class Feedback extends Component {
constructor(props) {
super(props);
this.state = {
technicalRating: '',
analyticalRating: '',
commRating:'',
}
}
onTechnicalRatingCom =() => {
//you code that you want to run after technical skill rating complete
}
onAnaliticalRatingCom = () => {
// you code that you want to run after analitical skill rating complete
}
onCommunicationRatingCom = () => {
// you code that you want to run after communication skill rating complete
}
render() {
return (
<View style={styles.row}>
<View style={styles.view}>
<Text style={styles.skillsText}>Technical Skills*</Text>
</View>
<RatingView onRatingCompleted={this.onTechnicalRatingCom} />
</View>
<View style={styles.row}>
<View style={styles.view}>
<Text style={styles.skillsText}>Analytical Skills*</Text>
</View>
<RatingView onRatingCompleted={this.onAnaliticalRatingCom} />
</View>
<View style={styles.row}>
<View style={styles.view}>
<Text style={styles.skillsText}>Communication*</Text>
</View>
<RatingView onRatingCompleted={this.onCommunicationRatingCom} />
</View>
)
}
}
export class RatingView extends Component {
constructor(props) {
super(props);
}
render() {
return <Rating
showRating
onFinishRating={this.props.onRatingCompleted}
style={{ marginRight: 10, marginTop: 6 }}
fractions={1}
imageSize={20}
showRating={false}
startingValue={0}
/>
}
}

Open ListView Photos in Modal

I want to use Modal with ListView and open That in renderRow(rowData){} Area But Does not open.
That is okey in render() Area But I Got: a red Screen Can't Find Variable: rowData
How Can I Fix That?
My Code:
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableHighlight, ListView, Image, Modal, Linking } from 'react-native';
import photosData from '../dataset/Photos'
var Dimensions = require('Dimensions')
var { width, height } = Dimensions.get('window')
export default class MyListView extends React.Component {
constructor(props) {
super(props)
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })
this.state = {
dataSource: ds.cloneWithRows(photosData),
modalVisible: false,
}
}
setModalVisible(visible) {
this.setState({ modalVisible: visible });
}
renderRow(rowData) {
const img = rowData.image
return (
<TouchableHighlight style={styles.containerCell}
// onPress={() => Linking.openURL(img)}
onPress={() => { this.setModalVisible(true) }}
>
<View>
<Image
// resizeMode={Image.resizeMode.contain}
// resizeMethod={"scale"}
style={{ width: width, height: 180, }}
source={{ uri: img }}
/>
<View style={styles.footerContainer}>
<View
style={styles.imageUser}
>
<Image
style={styles.imageAvatar}
// source={{ uri: rowData.user }}
source={require('../assets/icons/footer-avatar.png')}
/>
</View>
<View style={styles.footerTextContainer}>
<Text style={{ color: 'blue' }} //I can see my photos in webview
onPress={() => Linking.openURL(img)}>
Google
</Text>
<Text style={styles.text}>{rowData.food}</Text>
<Text style={[styles.text, styles.textTitle]}>{rowData.title}</Text>
<Text style={[styles.text, styles.textBy]}>By {rowData.by}</Text>
</View>
</View>
</View>
</TouchableHighlight>
)
}
render() {
const img = rowData.image
return (
<View style={styles.container}>
<Modal
animationType={"slide"}
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => { alert("Modal has been closed."), this.setModalVisible(!this.state.modalVisible) }}
>
<View style={{ marginTop: 22 }}>
<View>
<Image
// resizeMode={Image.resizeMode.contain}
// resizeMethod={"scale"}
style={{ width: width, height: 180, }}
source={{ uri: img }} // I can'ttttttttttt see my photos in Modal
/>
<TouchableHighlight onPress={() => {
this.setModalVisible(!this.state.modalVisible)
}}>
<Text>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
<ListView
style={styles.listContainer}
renderRow={this.renderRow.bind(this)}
dataSource={this.state.dataSource}
/>
</View>
);
}
}
I have pasted your code, it seem you have minor syntax error of closing bracket but I hope it is just copy-paste mistake.
First thing, you should not place your your Modal in renderRow function, it can create problem sometimes with styling and data. You can place it in main render() method.
Add function call to your rendering method if data is available and set this.setModalVisible(true).
Example:
render() {
return(
<View>
{/* other code */}
<Modal
animationType={'slide'}
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => { this.setModalVisible(false); } }
>
<View style={{ marginTop: 22 }}>
{(/*add some condition to check availability of data */)
? this.renderRow() // rendering function
: NULL}
</View>
</Modal>
</View>
);
}
EDIT after OP changed question:
Please find full code with my comment (not tested just added logic to work-around)
import React, { Component } from 'react';
import { View, Text, StyleSheet, TouchableHighlight, ListView, Image, Modal, Linking } from 'react-native';
import photosData from '../dataset/Photos'
var Dimensions = require('Dimensions')
var { width, height } = Dimensions.get('window')
export default class MyListView extends React.Component {
constructor(props) {
super(props)
const ds = new ListView.DataSource({ rowHasChanged: (r1, r2) => r1 !== r2 })
this.state = {
dataSource: ds.cloneWithRows(photosData),
modalVisible: false,
currentImage: ''
}
}
setModalVisible(visible, img) {
this.setState({ modalVisible: visible, currentImage: img }); // set current image path to show it in modal
}
renderRow(rowData) {
const img = rowData.image
return (
<TouchableHighlight style={styles.containerCell}
// onPress={() => Linking.openURL(img)}
onPress={() => { this.setModalVisible(true, img) }} // pass image scr to function
>
<View>
<Image
// resizeMode={Image.resizeMode.contain}
// resizeMethod={"scale"}
style={{ width: width, height: 180, }}
source={{ uri: img }}
/>
<View style={styles.footerContainer}>
<View
style={styles.imageUser}
>
<Image
style={styles.imageAvatar}
// source={{ uri: rowData.user }}
source={require('../assets/icons/footer-avatar.png')}
/>
</View>
<View style={styles.footerTextContainer}>
<Text style={{ color: 'blue' }} //I can see my photos in webview
onPress={() => Linking.openURL(img)}>
Google
</Text>
<Text style={styles.text}>{rowData.food}</Text>
<Text style={[styles.text, styles.textTitle]}>{rowData.title}</Text>
<Text style={[styles.text, styles.textBy]}>By {rowData.by}</Text>
</View>
</View>
</View>
</TouchableHighlight>
)
}
render() {
// const img = rowData.image
return (
<View style={styles.container}>
<Modal
animationType={"slide"}
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => { alert("Modal has been closed."), this.setModalVisible(!this.state.modalVisible) }}
>
<View style={{ marginTop: 22 }}>
<View>
<Image
// resizeMode={Image.resizeMode.contain}
// resizeMethod={"scale"}
style={{ width: width, height: 180, }}
source={{ uri: this.state.currentImage }} // use currentImage scr to show on clicking list item
/>
<TouchableHighlight onPress={() => {
this.setModalVisible(!this.state.modalVisible)
}}>
<Text>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
<ListView
style={styles.listContainer}
renderRow={this.renderRow.bind(this)}
dataSource={this.state.dataSource}
/>
</View>
);
}
}