I want to display image in my react native program which is taken from nasa api. I created a react native project:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
StatusBar,
Image
} from 'react-native';
import api from './utilities/api';
export default class test extends Component {
constructor(props){
super(props);
this.state ={
apod: [],
apodName: ''
}
}
componentWillMount(){
api.getApod().then((res)=> {
this.setState({
apod: res.apod,
apodName: res.url
})
});
}
render() {
console.log("Apod:", this.state.hdurl);
return (
<View>
<StatusBar
backgroundColor="#00FA9A"
barStyle="dark-content"
/>
<Text style={styles.welcome}>
Apod: {this.state.apodName}
</Text>
<Image source={{uri: api.hdurl}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
thumbnail: {
width: 53,
height: 81,
}
});
I also have api.js file :
var api ={
getApod(){
var url = 'https://api.nasa.gov/planetary/apod?api_key=MY KEY';
return fetch(url).then((res) => res.json());
}
};
module.exports = api;
Result I have on screen, its just writes an image link. But how to display actual image
Related
So I am using react-native-nfc-manager in my project that needs to scan the data from a nfc card but its just keep crashing on scanning. It is scanning data from another mobile correctly but keep crashing while scanning the card.
I have Used react-native-nfc-manager package
https://github.com/whitedogg13/react-native-nfc-manager
import React, { Component } from "react";
import { ScrollView, Alert, View, Text, StyleSheet } from "react-native";
import QRCode from "react-native-qrcode";
import { Button } from "native-base";
import { startNFC } from "./NFCHelper";
export default class POS_2MENU extends Component {
static navigationOptions = ({ navigation }) => ({ header: null });
constructor(props) {
super(props);
const { navigation } = this.props;
this.state = { tagValue: null, showProgress: false };
global.payer = navigation.getParam("wallet");
global.amount = navigation.getParam("amount");
global.token = navigation.getParam("token");
global.card = navigation.getParam("card");
}
componentWillMount() {
startNFC(this.handleNFCTagReading);
}
componentWillUnmount() {
// stopNFC();
}
handleNFCTagReading = nfcResult => {
if (nfcResult.Error) {
this.setState({ tagValue: nfcResult.Error.Message });
} else {
alert("nfc data show here");
}
};
render() {
return (
<ScrollView style={styles.homeView}>
{this.state.tagValue ? (
<Text style={styles.tagValue}>{this.state.tagValue}</Text>
) : null}
<View style={styles.container}>
<Button
style={styles.image1}
activeOpacity={0.5}
>
<Text style={{ color: "#fff", fontSize: 20, marginLeft: "18%" }}>
Tap Card Here
</Text>
</Button>
<QRCode
value={global.payer + "," + global.amount}
size={200}
bgColor="#000"
fgColor="#fff"
/>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
homeView: {
marginTop: 20,
marginBottom: 40
},
container: {
marginTop: 40,
marginLeft: "25%"
},
image1: {
backgroundColor: "#008CBA",
width: 200,
height: 200,
marginBottom: 40
},
tagValue: {
fontWeight: "bold",
fontSize: 16,
marginTop: 40,
paddingLeft: 40,
paddingRight: 40,
textAlign: "center"
}
});
I keep getting this error in my debug console..
This is my main App component code :-
import React, {Component} from 'react';
import {StyleSheet, Text, View, FlatList, Image} from 'react-native';
import Bookitem from "./Bookitem";
const mB = [
{
rank: 1,
title: "Gathering Prey",
author: "John Sanford",
image : "http://du.ec2.nytimes.com.s3.amazonaws.com/prd/books/9780399168796.jpg"
},
{
rank: 2,
title: "Memory Man",
author: "David Baldacci",
image : "http://du.ec2.nytimes.com.s3.amazonaws.com/prd/books/9781455586387.jpg"
}
];
export default class App extends Component {
constructor(props){
super(props);
this.state={data : this.addKeystoBooks(mB)};
}
addKeystoBooks = books => {
return books.map(book => {
return Object.assign(book,{key: book.title})
})
}
_renderitem = ({item}) => {
<Bookitem
coverURL = {item.image}
author = {item.author}
title = {item.key}
/>
}
render() {
return <FlatList
data={this.state.data}
renderItem={this._renderitem} />;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
flexDirection : 'row'
},
input : {
fontFamily: 'Lobster-Regular',
fontSize: 24,
padding: 40,
borderWidth: 2,
textAlign : "center"
}
});
My BookItem Component code is as follows :-
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
export default class book extends Component {
render(){
return(
<View style = {styles.container}>
<Image style = {styles.cover} source = {this.props.coverURL} resizeMode="contain" />>
<View style = {styles.info}>
<Text style = {styles.author}>{this.props.author}</Text>
<Text style ={styles.title}>{this.props.title}</Text>
</View>
</View>
)
}
}
const styles = StyleSheet.create(
{
container : {
flex:1,
justifyContent: "center",
alignItems: "center",
flexDirection: "row",
backgroundColor:"#FFFFFF",
borderBottomColor:"#AAAAAA",
borderBottomWidth: 2,
padding: 5,
height: 175
},
cover : {
flexDirection:"column",
alignItems: "flex-start",
height: 150
},
info:{
flexDirection: "column",
alignItems: "flex-end",
flex: 3,
alignSelf:"center",
padding: 20
},
author: {
fontFamily: "Lobster-regular",
fontSize: 20
},
title : {
fontSize: 23,
fontFamily: "Lobster-Regular"
}
}
)
I have used addkeystobooks function to add a unique identifier to each book for rendering of the flatList's data
I hope this information is sufficient enough to tell me where i am going wrong, i am trying to work with the react-native based on a mock book set..
My app has a background image which has a slightly transparent view placed over it to provide a blue tint to the background image. I am now trying to place the app logo on top of these views but when I do so the logo appears to take on the opacity of the view providing the tint.
I am very new to react native but what I basically need is to have: background image > view > logo.
To demonstrate what I mean, the app logo should look like this:
But it currently looks washed out, like this:
App.js
import React, { Component } from 'react';
import { View, Text, ImageBackground } from 'react-native';
import Logo from './Logo';
class App extends Component {
render() {
return (
<ImageBackground
source={require('./images/city.png')}
style={styles.backgroundStyle}
>
<View style={styles.backgroundOverlayStyle}>
<Logo />
</View>
</ImageBackground>
);
}
}
const styles = {
backgroundStyle: {
flex: 1,
backgroundColor: '#000000',
width: '100%',
height: '100%'
},
backgroundOverlayStyle: {
flex: 1,
backgroundColor: '#003284',
opacity: 0.5
}
};
export default App;
Logo.js
import React from 'react';
import { View, Image } from 'react-native';
const Logo = () => {
const { logoStyle } = styles;
return (
<View style={styles.container}>
<Image style={logoStyle} source={require('./images/request-first-logo-white.png')} />
</View>
);
};
const styles = {
container: {
alignItems: 'center',
justifyContent: 'center',
opacity: 1,
},
logoStyle: {
width: '70%',
height: '65%',
resizeMode: 'contain',
//backgroundColor: 'blue'
}
};
export default Logo;
Thank you for any help.
you need you define blurRadius for ImageBackground
import React, { Component } from 'react';
import { View, Text, ImageBackground,Image } from 'react-native';
const Logo = () => {
const { logoStyle } = styles;
return (
<View style={styles.container}>
<Image style={logoStyle} source={{uri:'https://www.what-dog.net/Images/faces2/scroll001.jpg'}} />
</View>
);
};
export default class App extends Component {
render() {
return (
<ImageBackground
source={{uri : 'https://pngstocks.com/wp-content/uploads/2018/03/cb-background-10.jpeg'}}
style={styles.backgroundStyle}
blurRadius={30}
>
<Logo />
</ImageBackground>
);
}
}
const styles = {
backgroundStyle: {
flex: 1,
backgroundColor: '#000000',
width: '100%',
height: '100%'
},
backgroundOverlayStyle: {
flex: 1,
backgroundColor: '#003284',
},
container: {
alignItems: 'center',
justifyContent: 'center',
},
logoStyle: {
width: 100,
height: 100,
resizeMode: 'contain',
//backgroundColor: 'blue'
}
};
I have a little problem with an app that I am working on. I have to make something like a note app. There for I have a button that navigates me to another screen where I can write the note and I have a save button that should send me back to the previews screen and the scrollview shold be updated
Here is what I've tried so far:
App.js:
import React, { Component } from 'react';
import Main from './app/components/Main.js';
import NoteBody from './app/components/NoteBody.js';
import {StackNavigator} from 'react-navigation'
const App = StackNavigator({Home: {screen: Main}, WriteNote: {screen: NoteBody}});
export default App;
Main.js:
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TextInput,
ScrollView,
TouchableOpacity,
AsyncStorage,
} from 'react-native';
import Note from './Note';
import NoteBody from './NoteBody.js';
export default class Main extends Component {
static navigationOptions = {
title: 'Notes',
};
constructor(props){
super(props);
this.state = {
noteArray: [],
noteText: '',
};
}
componentDidMount(){
this.getSavedNotes(this.state.noteArray);
}
render() {
let notes = this.state.noteArray.map((val, key)=>{
return <Note key={key} keyval={key} val={val}
deleteMethod={()=>this.deleteNote(key)}/>
});
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<ScrollView style={styles.scrollViewContainer}>
<ScrollView style={styles.scrollContainer}>
{notes}
</ScrollView>
<TouchableOpacity onPress={() =>
navigate('WriteNote' ,{onNavigateBack:
this.handleOnNavigateBack.bind(this)})}
style={styles.addButton}>
<Text style={styles.addButtonText}>+</Text>
<Text style={styles.addButtonAditionalText}>Add note</Text>
</TouchableOpacity>
</ScrollView>
</View>
);
}
deleteNote(key){
this.state.noteArray.splice(key, 1);
this.setState({noteArray: this.state.noteArray});
AsyncStorage.setItem('arr', JSON.stringify(this.state.noteArray));
// alert(this.state.noteArray);
}
getSavedNotes = async (noteArray) =>{
try{
let data = await AsyncStorage.getItem('arr');
if(JSON.parse(data))
{
this.setState({noteArray: JSON.parse(data)});
}
}catch(error){
alert(error);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
scrollContainer: {
flex: 1,
},
addButton: {
position: 'relative',
zIndex: 11,
left: 0,
top: 0,
alignItems: 'flex-start',
justifyContent: 'flex-end',
width: 100,
height: 60,
elevation: 8
},
addButtonText: {
color: '#000',
fontSize: 60,
},
addButtonAditionalText: {
color: '#000',
fontSize: 12,
marginLeft: 40,
position: 'absolute',
bottom: 20,
},
scrollViewContainer: {
flex: 1,
marginBottom: 70,
}
});
Note.js: Here we have the scrollview and the button that navigates you to the NoteBody screen.
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
} from 'react-native';
export default class Note extends Component {
render() {
return (
<View key={this.props.keyval} style={styles.note}>
<Text style={styles.noteText}>{this.props.val.date}</Text>
<Text style={styles.noteText}>{this.props.val.note}</Text>
<TouchableOpacity onPress={this.props.deleteMethod} style={styles.noteDelete}>
<Text style={styles.noteDeleteText}>Del</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
note: {
position: 'relative',
padding: 20,
paddingRight: 100,
borderBottomWidth:2,
borderBottomColor: '#ededed'
},
noteText: {
paddingLeft: 20,
borderLeftWidth: 10,
borderLeftColor: '#0000FF'
},
noteDelete: {
position: 'absolute',
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#2980b9',
padding: 10,
top: 10,
bottom: 10,
right: 10
},
noteDeleteText: {
color: 'white'
}
});
and finally NoteBody: Here is where you can write the body of the note and you have that save button that should also save the data in an AsyncStorage so I can display it even after the app is closed.
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TextInput,
TouchableOpacity,
AsyncStorage,
} from 'react-native';
import Note from './Note.js';
export default class NoteBody extends Component {
static navigationOptions = {
title: 'Note',
};
constructor(props){
super(props);
this.state = {
noteArray: [],
noteText: '',
};
}
componentDidMount(){
this.getSavedNotes(this.state.noteArray);
}
render() {
let notes = this.state.noteArray.map((val, key)=>{
return <Note key={key} keyval={key} val={val}
deleteMethod={()=>this.deleteNote(key)}/>
});
return (
<View style={styles.container}>
<View style={styles.noteBody}>
<TextInput
multiline = {true}
numberOfLines = {1000000}
style={styles.textInput}
placeholder='Write your note here'
onChangeText={(noteText)=> this.setState({noteText})}
value={this.state.noteText}
placeholderTextColor='grey'
underlineColorAndroid='transparent'>
</TextInput>
</View>
<TouchableOpacity onPress={ this.addNote.bind(this) } style={styles.addButton}>
<Text style={styles.addButtonText}>SAVE</Text>
</TouchableOpacity>
</View>
);
}
addNote(){
const { navigate } = this.props.navigation;
if(this.state.noteText){
var d = new Date();
this.state.noteArray.push({
'date':d.getFullYear()+
"/"+(d.getMonth()+1) +
"/"+ d.getDate(),
'note': this.state.noteText
});
this.setState({ noteArray: this.state.noteArray });
this.setState({noteText:''});
AsyncStorage.setItem('arr', JSON.stringify(this.state.noteArray));
this.props.navigation.state.params.onNavigateBack();
navigate('Home');
// alert(this.state.noteArray);
}
}
getSavedNotes = async (noteArray) =>{
try{
let data = await AsyncStorage.getItem('arr');
if(JSON.parse(data))
{
this.setState({noteArray: JSON.parse(data)});
}
}catch(error){
alert(error);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
noteBody:{
position: 'absolute',
top: 0,
bottom: 0,
left: 0,
right: 0,
zIndex: 10,
alignItems: 'center',
borderBottomWidth:1,
borderTopColor: '#000',
marginBottom: 100,
},
textInput: {
alignSelf: 'stretch',
textAlignVertical: 'top',
backgroundColor: '#fff',
color: '#000',
padding: 20,
borderTopWidth:2,
borderTopColor: '#ededed',
},
addButton: {
position: 'absolute',
zIndex: 11,
left: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center',
width: 300,
backgroundColor: '#00FF00',
height: 60,
elevation: 8
},
addButtonText: {
color: '#fff',
fontSize: 24,
},
});
The save button only saves the last note I wrote and it doesn't even show it on the scrollview immediately. I have to reopen the app to display it.
There are a couple of things which are wrong here:
First you only fetch the saved notes in the constructor of your Main component, which only gets called on instantiation. The recommended place to put this code is in componentDidMount(). Also I don't understand why you are are passing the noteArray state to your getSavedNotes() method.
Next, and this is an important one: your methods to add and delete notes from the array are mutating (splice and push). Since React uses shallow comparison to determine when to re-render, you need to create a new object when using setState(). So for additions you could use concat() and for deletions the omit() function of Lodash is very useful. Alternatively you could use the spread operator.
Disclaimer: I haven't yet read all of your code in detail, so there might still be some additional problems.
Edit: with FlatList
// render() method of Main.js
render() {
const { navigate } = this.props.navigation;
return (
<View style={styles.container}>
<ScrollView style={styles.scrollViewContainer}>
<ScrollView style={styles.scrollContainer}>
<FlatList
data={this.state.noteArray}
renderItem={({item, index}) => this.renderItem(item, index)}
keyExtractor={(item, index) => `${index}`}
/>
</ScrollView>
<TouchableOpacity onPress={() =>
navigate('WriteNote')}
style={styles.addButton}>
<Text style={styles.addButtonText}>+</Text>
<Text style={styles.addButtonAditionalText}>Add note</Text>
</TouchableOpacity>
</ScrollView>
</View>
);
}
renderItem = (item, index) => {
return (
<Note
keyval={index}
val={item}
deleteMethod={()=>this.deleteNote(index)}
/>
);
}
It looks like you could add a listener in Main.js for 'onFocus' events. I would use the callback to query AsyncStorage and set state with the result.
Screen A
Method to do the thing in Screen A that you want to happen when navigating back from Screen B:
handleOnNavigateBack = (foo) => {
this.setState({
foo
})
}
This is the React Navigation method in Screen A to navigate to Screen B:
this.props.navigation.navigate('ScreenB', {
onNavigateBack: this.handleOnNavigateBack})
…or if your handleOnNavigateBack function is not a arrow function (which binds this) you'll need to bind this: (ht #stanica)
this.props.navigation.navigate('ScreenB', {
onNavigateBack: this.handleOnNavigateBack.bind(this)
})
Screen B
After navigating to Screen B and ready to Navigate back to Screen A…
Call the function (passed to Screen B from Screen A) to do the thing in Screen A:
this.props.navigation.state.params.onNavigateBack(this.state.foo)
Then call the React Navigation method to go Back (to Screen A):
this.props.navigation.goBack()
I also updated my question's code so it is the version that dose what is suppose to do.
I have problem in changing value of state.It gives mi following error
"Undefine is not a function(evaluating '
this.setState({
switchValue:false
})')"
I have search on stack overflow but the solution is not work for me.
import React, { Component } from 'react';
import {
Alert,
AppRegistry,
StyleSheet,
Text,
View,
Switch
} from 'react-native';
export default class AwesomeProject extends Component {
constructor(props) {
super(props);
this.state = {switchValue: true};
// Toggle the state every second
}
_onPressButton() {
this.setState({
switchValue: false
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Switch
onValueChange={this._onPressButton}
value={this.state.switchValue }
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
The this inside _onPressButton is not referencing the correct reference. On that case, this inside that _onPressButton is actually reference the button. You can either do this two ways.
<Switch
onValueChange={this._onPressButton.bind(this)}
value={this.state.switchValue }
/>
Or
<Switch
onValueChange={() => this._onPressButton()}
value={this.state.switchValue }
/>