UPDATED CODE
This now fetches the data when button clicked but I cant display it as it did when it loaded first time?
I am totally new with react native so I am sorry if I explain my problem wrong or seem a little thick. I have made a screen that fetches data and displays the data and it seems to work quite well. However I have a couple of buttons and I want to add an onclick to call a function.
Maybe I am getting this wrong but its supposed to work like javascript which I have no problem with but I think I am missing something with the difference between components and functions.
For example in my code its just automatically fetches the data and displays it. How would I make functions to load the data when one the buttons is clicked and also update the view with the new loaded data?
I have tried putting the functions in with the fetch data but I seem to have to add everything but surely I can make re-usable functions for each task like I would in javascript.
I have included my code for the page and also what I have tried. Any help of advice would be great as when I am researching on the net I get confused information between reactjs and native.
Also all the code below has been snippets taken from various places and played around with so it is totally probably all wrong in terms of structure.
The code :
import React from "react";
import {
StyleSheet,
View,
ActivityIndicator,
FlatList,
Text,
StatusBar,
Image,
TouchableOpacity,
ScrollView,
SafeAreaView
} from "react-native";
import Icon from "react-native-vector-icons/Entypo";
import CupertinoButtonPurple1 from "../components/CupertinoButtonPurple1";
import Removebutton from "../components/removebutton";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
loading: true,
dataSource:[] };
}
componentDidMount(){
fetch("https://www.uberfantasies.com/testv2.php")
.then(response => response.json())
.then((responseData)=> {
this.setState({
loading: false,
dataSource: responseData.data
})
})
.catch(error=>console.log(error)) //to catch the errors if any
}
FlatListItemSeparator = () => {
return (
<View/>
);
}
renderItem=(data)=>
<SafeAreaView>
<View style={styles.container}>
<View style={styles.rect}>
<View style={styles.imageRow}>
<Image source={{uri: data.item.image}} style={styles.image} />
<View style={styles.group2Column}>
<View style={styles.group2}>
<Text style={styles.bitch}>
<Text>{data.item.from} sent you a mesage!</Text>
</Text>
<Text style={styles.loremIpsum}>
"{data.item.message}"
</Text>
</View>
<View style={styles.loremIpsum2Row}>
<Text style={styles.loremIpsum2}>{data.item.when}</Text>
<View style={styles.loremIpsum2Filler}></View>
<View style={styles.group3}>
<CupertinoButtonPurple1
style={styles.cupertinoButtonPurple1}
></CupertinoButtonPurple1>
<Removebutton
style={styles.removebutton}
></Removebutton>
</View>
</View>
</View>
</View>
</View>
</View>
</SafeAreaView>
render(){
if(this.state.loading){
return(
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9"/>
</View>
)}
return(
<View style={styles.container}>
<FlatList
data= {this.state.dataSource}
ItemSeparatorComponent = {this.FlatListItemSeparator}
renderItem= {item=> this.renderItem(item)}
keyExtractor= {item=>item.id.toString()}
/>
</View>
)}
}
const styles = StyleSheet.create({
container: {
flex: 1
},
loader:{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
},
rect: {
height: 97,
backgroundColor: "rgba(230,230, 230,0.57)",
borderWidth: 0,
borderColor: "rgba(0,0,0,0.57)",
marginTop: 0,
borderBottomWidth: 1,
borderBottomColor: "#d5d5d5",
backgroundColor: "#f4f4f4"
},
image: {
width: 80,
height: 80,
borderRadius: 15,
borderWidth: 4,
borderColor: '#ffffff',
shadowColor: '#d5d5d5',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.8,
shadowRadius: 2
},
group2: {
height: 41
},
bitch: {
fontFamily: "sans-serif-condensed",
color: "#121212",
fontSize: 14,
height: 17,
fontWeight: "bold",
marginTop: 2
},
loremIpsum: {
fontFamily: "sans-serif-condensed",
color: "#121212",
height: 17,
width: 159,
marginTop: 4
},
loremIpsum2: {
fontFamily: "sans-serif-condensed",
color: "#121212",
fontSize: 10,
marginTop: 8
},
loremIpsum2Filler: {
flex: 1,
flexDirection: "row"
},
group3: {
width: 125,
height: 26,
flexDirection: "row",
justifyContent: "space-between",
marginRight: 25
},
cupertinoButtonPurple1: {
height: 25,
width: 57
},
cupertinoButtonDanger2: {
height: 25,
width: 57
},
loremIpsum2Row: {
height: 26,
flexDirection: "row",
marginTop: 17,
marginRight: 33,
width: "100%"
},
group2Column: {
width: 275,
marginLeft: 16
},
imageRow: {
height: 84,
flexDirection: "row",
marginTop: 8,
marginLeft: 4
}
});
and the way I have tried to make a function and the way I think it should work with results?
The UPDATED code that fetches data but I cant get it to display data how it did in the previous code? Going out my nut here because I think Im missing something silly. If I had only one element to display or change I could do it but I think its because it looks through the results? Am i wrong?
Heres the code:
import React, { useState, Component } from 'react'
import {
StyleSheet,
View,
ActivityIndicator,
FlatList,
Text,
StatusBar,
Image,
TouchableOpacity,
ScrollView,
SafeAreaView
} from 'react-native'
class App extends Component {
state = {
loading: true,
dataSource:[],
Status: "Not loaded"
}
onPress = () => {
fetch("https://www.uberfantasies.com/testv.php")
.then(response => response.json())
.then((responseData)=> {
this.setState({
loading: false,
Status: "Loaded",
dataSource: responseData.data
})
console.log(this.state.dataSource)
})
.catch(error=>console.log(error)) //to catch the errors if any
}
render() {
return (
<View style={styles.container}>
<TouchableOpacity
style={styles.button}
onPress={this.onPress}
>
<Text>Click me</Text>
</TouchableOpacity>
<View>
<Text>
Status : { this.state.Status }
</Text>
</View>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
marginBottom: 10
},
loader:{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#fff"
}
})
export default App;
if you want to call a function within onPress you need to call it. Like
<Button title="Press Me" onPress={() => ReloadData()} />
Below is a sample code snippet. I have used the function component as it is easy for a beginner. Assuming your output of the API call is a list, I am setting it to the state variable. SO whenever the 'apiData' variable value changes your component will re-render. You can user either a button or a touchable wrapper component for a clickable item.
const [apiData, setApiData] = useState([]);
const MySampleComponent = () => {
const apiCall = () => {
//Your code
setApiData(result);
};
const renderListItem = (itemData) => <Text>{itemData.item.<your key>}</Text>;
return (
<View>
<FlatList
keyExtractor={item => item.id}
data={apiData}
renderItem={renderListItem}
/>
<Button onPress={apiCall} />
<TouchableOpacity onPress={apiCall}>
<Text>Click Me</Text>
</TouchableOpacity>
</View>
);
};
Thanks for your comments and help, I think I have a much better way of understanding a few things now. I have managed to get a load button to fetch data and display it in the way as previously managed. I know it does not look like much progress but trust me this is a big step to getting to grips with the way things work for me.
Now time to play around with it, thanks again.
The working code (well best I can do at the minute!)
import React, { useState, Component } from 'react';
import {
StyleSheet,
View,
ActivityIndicator,
FlatList,
Text,
StatusBar,
Image,
TouchableOpacity,
ScrollView,
SafeAreaView,
} from 'react-native';
import Icon from 'react-native-vector-icons/Entypo';
import CupertinoButtonPurple1 from '../components/CupertinoButtonPurple1';
import CupertinoButtonDanger2 from '../components/CupertinoButtonDanger2';
class App extends Component {
state = {
loading: false,
dataSource: [],
Status: 'Not loaded',
};
componentDidMount() {
// this.onPress();
}
onPress = () => {
this.setState({
loading: true,
});
fetch('https://www.uberfantasies.com/testv.php')
.then((response) => response.json())
.then((responseData) => {
this.setState({
loading: false,
Status: 'Loaded',
dataSource: responseData.data,
});
console.log(this.state.dataSource);
})
.catch((error) => console.log(error)); //to catch the errors if any
};
FlatListItemSeparator = () => {
return <View />;
};
renderItem = (data) => (
<SafeAreaView>
<View style={styles.container}>
<View style={styles.rect}>
<View style={styles.imageRow}>
<Image source={{ uri: data.item.image }} style={styles.image} />
<View style={styles.group2Column}>
<View style={styles.group2}>
<Text style={styles.bitch}>
Bitch from Cov sent you a mesage!
</Text>
<Text style={styles.loremIpsum}>
"Hi there you Sexy Beast!"
</Text>
</View>
<View style={styles.loremIpsum2Row}>
<Text style={styles.loremIpsum2}>12 Feb 2022, 6.05 pm</Text>
<View style={styles.loremIpsum2Filler}></View>
<View style={styles.group3}>
<CupertinoButtonPurple1
style={
styles.cupertinoButtonPurple1
}></CupertinoButtonPurple1>
<CupertinoButtonDanger2
style={
styles.cupertinoButtonDanger2
}></CupertinoButtonDanger2>
</View>
</View>
</View>
</View>
</View>
</View>
</SafeAreaView>
);
render() {
if (this.state.loading) {
return (
<View style={styles.loader}>
<ActivityIndicator size="large" color="#0c9" />
</View>
);
}
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={this.onPress}>
<Text>Click me</Text>
</TouchableOpacity>
<View>
<Text>Status : {this.state.Status}</Text>
</View>
<FlatList
data={this.state.dataSource}
ItemSeparatorComponent={this.FlatListItemSeparator}
renderItem={(item) => this.renderItem(item)}
keyExtractor={(item) => item.id.toString()}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
button: {
alignItems: 'center',
backgroundColor: '#DDDDDD',
padding: 10,
marginBottom: 10,
},
loader: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
rect: {
height: 97,
backgroundColor: 'rgba(230,230, 230,0.57)',
borderWidth: 0,
borderColor: 'rgba(0,0,0,0.57)',
marginTop: 0,
borderBottomWidth: 1,
borderBottomColor: '#d5d5d5',
backgroundColor: '#f4f4f4',
},
image: {
width: 80,
height: 80,
borderRadius: 15,
borderWidth: 4,
borderColor: '#ffffff',
boxShadow: '0px 2px 4px 0px rgb(0 0 0 / 55%)',
},
group2: {
width: 275,
height: 41,
},
bitch: {
fontFamily: '-apple-system,Segoe UI,Roboto,sans-serif',
color: '#121212',
fontSize: 14,
height: 17,
fontWeight: 'bold',
marginTop: 2,
},
loremIpsum: {
fontFamily: '-apple-system,Segoe UI,Roboto,sans-serif',
color: '#121212',
height: 17,
width: 159,
marginTop: 4,
},
loremIpsum2: {
fontFamily: '-apple-system,Segoe UI,Roboto,sans-serif',
color: '#121212',
fontSize: 10,
marginTop: 8,
},
loremIpsum2Filler: {
flex: 1,
flexDirection: 'row',
},
group3: {
width: 121,
height: 26,
flexDirection: 'row',
justifyContent: 'space-between',
},
cupertinoButtonPurple1: {
height: 25,
width: 57,
},
cupertinoButtonDanger2: {
height: 25,
width: 57,
},
loremIpsum2Row: {
height: 26,
flexDirection: 'row',
marginTop: 17,
marginRight: 3,
},
group2Column: {
width: 275,
marginLeft: 16,
},
imageRow: {
height: 84,
flexDirection: 'row',
marginTop: 8,
marginLeft: 4,
},
});
export default App;
I'm trying to do something like that last image, the one that has the product detail to add to cart with the blurred background
Is there a way to make that floating screen in react navite?
I'm looking for something maybe similar to it, I don't really care about the content inside of it, just the general screen popup
I dont know how its called, so pointing me in a direction to do research or just naming it so I can google it would very much be appreciated it
It's called Modal and you can use React Native's component to present it. Check for official documentation https://reactnative.dev/docs/modal
For the blur part, you can use this library https://github.com/Kureev/react-native-blur
Here is a sample code to show the modal:
import React, { useState } from "react";
import { Alert, Modal, StyleSheet, Text, Pressable, View } from "react-native";
const App = () => {
const [modalVisible, setModalVisible] = useState(false);
return (
<View style={styles.centeredView}>
<Modal
animationType="slide"
transparent={true}
visible={modalVisible}
onRequestClose={() => {
Alert.alert("Modal has been closed.");
setModalVisible(!modalVisible);
}}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Hello World!</Text>
<Pressable
style={[styles.button, styles.buttonClose]}
onPress={() => setModalVisible(!modalVisible)}
>
<Text style={styles.textStyle}>Hide Modal</Text>
</Pressable>
</View>
</View>
</Modal>
<Pressable
style={[styles.button, styles.buttonOpen]}
onPress={() => setModalVisible(true)}
>
<Text style={styles.textStyle}>Show Modal</Text>
</Pressable>
</View>
);
};
const styles = StyleSheet.create({
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: 4,
elevation: 5
},
button: {
borderRadius: 20,
padding: 10,
elevation: 2
},
buttonOpen: {
backgroundColor: "#F194FF",
},
buttonClose: {
backgroundColor: "#2196F3",
},
textStyle: {
color: "white",
fontWeight: "bold",
textAlign: "center"
},
modalText: {
marginBottom: 15,
textAlign: "center"
}
});
export default App;
I'm new to react native, and I facing a problem to positioning my text.
I wanted to have something like this:
Hi, Daffa
XII RPL
but this my result:
Hi, Daffa XII RPL
here's my code:
import React from 'react';
import {View, StyleSheet, Text, Image} from 'react-native';
export default function Header() {
return (
<View style={styles.header}>
<Image style={styles.img} source={require('../assets/me.png')} />
<Text style={styles.text}>Hi, Daffa Quraisy</Text>
<Text style={styles.kelas}>XII RPL</Text>
</View>
);
}
const styles = StyleSheet.create({
header: {
height: 200,
backgroundColor: '#327fe3',
flexDirection: 'row',
alignItems: 'center',
},
img: {
height: 50,
width: 50,
marginLeft: 20,
padding: 0,
},
text: {
color: 'white',
marginLeft: 18,
fontWeight: 'bold',
},
kelas: {
color: 'white',
fontSize: 12,
marginLeft: 18,
flexWrap: 'nowrap',
},
});
thanks for reading this, I'm sorry if my question is kinda stupid, and sorry for my bad english.
Working App: Expo snack
Wrap Text components in View component:
import React from 'react';
import { View, StyleSheet, Text, Image } from 'react-native';
export default function Header() {
return (
<View style={styles.header}>
<Image style={styles.img} source={require('./assets/snack-icon.png')} />
<View>
<Text style={styles.text}>Hi, Daffa Quraisy</Text>
<Text style={styles.kelas}>XII RPL</Text>
</View>
</View>
);
}
const styles = StyleSheet.create({
header: {
height: 200,
backgroundColor: '#327fe3',
flexDirection: 'row',
alignItems: 'center',
},
img: {
height: 50,
width: 50,
marginLeft: 20,
padding: 0,
},
text: {
color: 'white',
marginLeft: 18,
fontWeight: 'bold',
},
kelas: {
color: 'white',
fontSize: 12,
marginLeft: 18,
flexWrap: 'nowrap',
},
});
you can use {\n} this tag to break line
<View style={styles.header}>
<Image style={styles.img} source={require('../assets/me.png')} />
<Text style={styles.text}>Hi, Daffa Quraisy {`\n`} <Text style={styles.kelas}>
XII RPL</Text>
</Text>
</View>
The <View> element is the default value column but you header class with change row. New <View> element wrapper texts for your fix.
I am trying to store the value of the color and the font size that the user has entered, but my program doesnt store the value, it changes it instantly when the user inputs text. I want it to change the font and background color when 'press me' is clicked. Here is what ive so far:
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, TextInput, Button, TouchableOpacity, Alert } from 'react-native';
function Input(props) {
return (
<TextInput
{...props}
style={{ height: 40, borderWidth: 1, padding: 20, paddingTop: 10, margin: 5 }}
editable
maxLength={40}
/>
);
}
export default function InputMultiline() {
const [mySize, setMySize] = useState('20');
const [myBGColor, setMyColor] = useState('yellow');
const colChange = () => {
setMyColor(myBGColor);
setMySize(mySize);
}
return (
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: myBGColor.toLowerCase(),
borderBottomColor: '#000000',
borderBottomWidth: 1,
}}>
<Text style={{ fontSize: Number(mySize) }}>Hello</Text>
<View>
<Input
multiline
numberOfLines={4}
value={myBGColor}
onChangeText={colText => setMyColor(colText)}
/></View>
<View>
<Input
multiline
numberOfLines={4}
value={mySize}
onChangeText={sizeText => setMySize(sizeText)}
/></View>
<View style={styles.fixToText}>
<TouchableOpacity>
<Button onPress={colChange}
title="Press Me!"
color="#841584" />
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
marginHorizontal: 16,
},
title: {
textAlign: 'center',
marginVertical: 8,
fontSize: 20
},
fixToText: {
flexDirection: 'row',
justifyContent: 'space-between',
},
separator: {
marginVertical: 8,
borderBottomColor: '#737373',
borderBottomWidth: StyleSheet.hairlineWidth,
},
});
I have no clue how to change the font and background color together and click on 'press me'.
You should add 2 more states that will contain user's input:
export default function InputMultiline() {
const [mySize, setMySize] = useState('20');
const [myBGColor, setMyColor] = useState('yellow');
const [mySizeUserInput, setMySizeUserInput] = useState('20'); <---- ADDED
const [myBGColorUserInput, setMyColorUserInput] = useState('yellow'); <----- ADDED
const colChange = () => {
setMyColor(myBGColorUserInput); <----- CHANGED
setMySize(mySizeUserInput); <----- CHANGED
}
return (
<View
style={{
flex: 1,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: myBGColor.toLowerCase(),
borderBottomColor: '#000000',
borderBottomWidth: 1,
}}>
<Text style={{ fontSize: Number(mySize) }}>Hello</Text>
<View>
<Input
multiline
numberOfLines={4}
value={myBGColor}
onChangeText={colText => setMyColorUserInput(colText)} <----- CHANGED
/></View>
<View>
<Input
multiline
numberOfLines={4}
value={mySize}
onChangeText={sizeText => setMySizeUserInput(sizeText)} <----- CHANGED
/></View>
<View style={styles.fixToText}>
<TouchableOpacity>
<Button onPress={colChange}
title="Press Me!"
color="#841584" />
</TouchableOpacity>
</View>
</View>
);
Se tu
I was able to reproduce the issue with your codes, in my case styles were broken so you can try to change the view by removing flex and adding height, like this:
<View style={{
alignItems: 'center',
justifyContent: 'center',
backgroundColor: myBGColor.toLowerCase(),
height: 100,
}}>
I am trying to use an icon "ic_shuffle_white.png" and the image is clearly in my directory, so I am not sure why I am getting the "Unable to resolve..." error.
I restarted my Xcode after adding the pngs, imported Image from react-native, and there does not appear to be a syntax error.
I am following this guide: https://hackernoon.com/building-a-music-streaming-app-using-react-native-6d0878a13ba4
Is it because I am using expo? or is the guide too old?
Screenshot:
Code:
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
Image,
TouchableOpacity,
} from 'react-native';
const Controls = ({
paused,
shuffleOn,
repeatOn,
onPressPlay,
onPressPause,
onBack,
onForward,
onPressShuffle,
onPressRepeat,
forwardDisabled,
}) => (
<View style={styles.container}>
<TouchableOpacity activeOpacity={0.0} onPress={onPressShuffle}>
<Image style={[styles.secondaryControl, shuffleOn ? [] : styles.off]}
source={require('../img/ic_shuffle_white.png')}/>
</TouchableOpacity>
<View style={{width: 40}} />
<TouchableOpacity onPress={onBack}>
<Image source={require('../img/ic_skip_previous_white_36pt.png')}/>
</TouchableOpacity>
<View style={{width: 20}} />
{!paused ?
<TouchableOpacity onPress={onPressPause}>
<View style={styles.playButton}>
<Image source={require('../img/ic_pause_white_48pt.png')}/>
</View>
</TouchableOpacity> :
<TouchableOpacity onPress={onPressPlay}>
<View style={styles.playButton}>
<Image source={require('../img/ic_play_arrow_white_48pt.png')}/>
</View>
</TouchableOpacity>
}
<View style={{width: 20}} />
<TouchableOpacity onPress={onForward}
disabled={forwardDisabled}>
<Image style={[forwardDisabled && {opacity: 0.3}]}
source={require('../img/ic_skip_next_white_36pt.png')}/>
</TouchableOpacity>
<View style={{width: 40}} />
<TouchableOpacity activeOpacity={0.0} onPress={onPressRepeat}>
<Image style={[styles.secondaryControl, repeatOn ? [] : styles.off]}
source={require('../img/ic_repeat_white.png')}/>
</TouchableOpacity>
</View>
);
export default Controls;
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center',
paddingTop: 8,
},
playButton: {
height: 72,
width: 72,
borderWidth: 1,
borderColor: 'white',
borderRadius: 72 / 2,
alignItems: 'center',
justifyContent: 'center',
},
secondaryControl: {
height: 18,
width: 18,
},
off: {
opacity: 0.30,
}
})