Why isn't react native displaying my background image? - android

The following code below compiles into react native just fine and the I don't recieve any errors in any of the compilers but my android emulator remains blank instead of displaying a background image like it's suppose to. Does anyone know why?
Code:
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ImageBackground} from 'react-native';
import bgImage from './Images/background.jpg'
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View>
<ImageBackground source={bgImage} style={styles.backgroundContainer}>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
backgroundContainer: {
flex: 1,
width:null,
height:null,
justifyContent: 'center',
alignItems: 'center',
},
});

Try this way
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, ImageBackground} from 'react-native';
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View>
<ImageBackground source={require(./Images/background.jpg)} style={styles.backgroundContainer}>
<Text> Here Background Image </Text>
</ImageBackground>
</View>
);
}
}
const styles = StyleSheet.create({
backgroundContainer: {
flex: 1,
width:'100%',
height:'100%',
},
});

You should use require
<ImageBackground soure={require(bgImage)} style={styles.backgroundContainer}>
</ImageBackground>

source={require(BgIMage)} You missed the require

Related

Text strings must be rendered within a <Text> component. (on both android and ios...running in expo)

I am trying to run the below code, but it throws the error "Text strings must be rendered within a <Text> component." I am using expo as of now. It reports no logs. The log section is empty.
import React, { useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';
export default function App() {
const [focusSubject, setFocusSubject] = useState(null);
return (
<View style={styles.container}>
focusSubject ? (
<Text>Screen 1</Text>
) : (
<Text>Screen 2</Text>
)
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#252250',
},
});
You need to use conditions in {} .
import React, { useState } from 'react';
import { View, StyleSheet, Text } from 'react-native';
export default function App() {
const [focusSubject, setFocusSubject] = useState(null);
return (
<View style={styles.container}>
{focusSubject ? (
<Text>Where am I going to build a timer</Text>
) : (
<Text />
)}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#252250',
},
});

React Native Alert.alert() only works on iOS and Android not web

I just started learning and practicing React Native and I have run into the first problem that I cant seem to solve by myself.
I have the following code, which is very simple, but the Alert.alert() does not work when I run it on the web. if I click the button nothing happens, however, when i click the button on an iOS or android simulator it works fine.
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, Button, View, Alert } from 'react-native';
export default function App() {
return (
<View style={styles.container}>
<Text style={styles.headerStyle} >Practice App</Text>
<Text style={{padding: 10}}>Open up App.js to start working on your app!</Text>
<Button
onPress={() => alert('Hello, Nice To Meet You :)')}
title="Greet Me"
/>
<StatusBar style="auto" />
</View>
);
}
I also know that alert() works on all three devices, however, I want to understand why Alert.alert() only works for iOS and Android.
My question is more so for understanding rather than finding a solution. Is the only solution to use alert(), or am I implementing Alert.alert() in the wrong way?
This workaround basically imitates react-native's Alert behavior with browsers' window.confirm method:
# alert.js
import { Alert, Platform } from 'react-native'
const alertPolyfill = (title, description, options, extra) => {
const result = window.confirm([title, description].filter(Boolean).join('\n'))
if (result) {
const confirmOption = options.find(({ style }) => style !== 'cancel')
confirmOption && confirmOption.onPress()
} else {
const cancelOption = options.find(({ style }) => style === 'cancel')
cancelOption && cancelOption.onPress()
}
}
const alert = Platform.OS === 'web' ? alertPolyfill : Alert.alert
export default alert
Usage:
Before:
import { Alert } from 'react-native'
Alert.alert(...)
After:
import alert from './alert'
alert(...)
Source & Credits: https://github.com/necolas/react-native-web/issues/1026#issuecomment-679102691
React Native is an open-source mobile application framework for Android, iOS and Web but there is not an Alert Component for Web but I have found a package which will provide you solutation. That is it to install package
npm i react-native-awesome-alerts
This example will help you
import React from "react";
import { StyleSheet, Text, View, TouchableOpacity } from "react-native";
import Alert from "react-native-awesome-alerts";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { showAlert: false };
}
showAlert = () => {
this.setState({
showAlert: true,
});
};
hideAlert = () => {
this.setState({
showAlert: false,
});
};
render() {
const { showAlert } = this.state;
return (
<View style={styles.container}>
<Text>Practice App</Text>
<Text style={{ padding: 10 }}>
Open up App.js to start working on your app!
</Text>
<TouchableOpacity
onPress={() => {
this.showAlert();
}}
>
<View style={styles.button}>
<Text style={styles.text}>Greet Me</Text>
</View>
</TouchableOpacity>
<Alert
show={showAlert}
message="Hello, Nice To Meet You :"
closeOnTouchOutside={true}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: "center",
justifyContent: "center",
backgroundColor: "#fff",
},
button: {
margin: 10,
paddingHorizontal: 10,
paddingVertical: 7,
borderRadius: 5,
backgroundColor: "#AEDEF4",
},
text: {
color: "#fff",
fontSize: 15,
},
});

type is invalid -- expected a string, react-native error

I'm new at React-Native. I'm trying to build an app on mobile. But when I run this code I'm getting this error: React.createElement: type is invalid -- expected a string (for built-in components). My App.js:
import React from 'react';
import { StyleSheet, View } from 'react-native';
import { Header } from './components/Header';
export default function App() {
return (
<View style={styles.screen}>
<Header title="guess a number"/>
</View>
);
}
const styles = StyleSheet.create({
screen:{
flex: 1
}
});
My Header.js:
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
const Header = props => {
return(
<View style={styles.header}>
<Text style={styles.headerTitle}> {props.title}</Text>
</View>
);
};
const styles=StyleSheet.create({
header: {
width:'100%',
height:90,
paddingTop: 36,
backgroundColor:'#f7287b',
alignItems: 'center',
justifyContent: 'center'
},
headerTitle: {
color:'black',
fontSize: 18
}
});
export default Header;
What should i do?
error
Your import of Header component is wrong. Import it as such :
import Header from './components/Header';
This is because you've exported as default in your Header.js File, so you need to import directly without {} brackets
Try to use:
<Header title={'guess a number'}/>

React Native Router Flux - expected a component class, got [object Object] when click a button to go to another screen

I am getting component class got object error while using react-native-router-flux, Here is my app.js file and component files.
app.js
import * as React from 'react';
import { Text, View, StyleSheet } from 'react-native';
import ScarletScreen from './components/ScarletScreen';
import GrayScreen from './components/GrayScreen';
import {Router, Scene} from 'react-native-router-flux';
const App = () => {
return (
<Router>
<Scene key = "root">
<Scene
key = "scarlet"
component = {ScarletScreen }
title = "Scarlet"
initial
/>
<Scene
key = "gray"
component = { GrayScreen }
title = "Gray"
/>
</Scene>
</Router>
);
}
export default App;
ScarletScreen.js
import React, { Component } from 'react';
import { Text, View, Button } from 'react-native';
import { Actions } from 'react-native-router-flux';
const ScarletScreen = () => {
return (
<View
style={{
backgroundColor: '#bb0000',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
}}>
<Text>Scarlet Screen</Text>
<Button title="IR PARA GRAY" onPress={() => Actions.gray()} />
</View>
);
};
export default ScarletScreen;
GrayScreen.js
import React, { Component } from 'react';
import {Text, View} from 'react-native';
import { Actions } from 'react-native-router-flux';
const GrayScreen = () => {
return(
<View style={{backgroundColor: '#666666', flex: 1, alignItems: 'center', justifyContent: 'center'}}>
<Text>Gray Screen</Text>
</View>
);
};
When I click on a button, the error "element type is invalid: expected a string" is shown.
You need to ensure all your components are exported. GrayScreen is missing the export.
export default Grayscreen

react native navigate to screen from function

I'm trying to move through screens using React Navigation, the problem lies in the nested return that i use to dynamically render a set of items and doesn't let me use an arrow function to directly navigate, so i have to implement this on a function. My question here is, how do i do that? As far as my internet research went you can only push a new screen after a dialog alert shows up, i don't want that.
I'm attaching the code:
var Dimensions = require('Dimensions');
var {width,height} = Dimensions.get('window');
import React, {Component} from 'react';
import {
View,
Text,
StyleSheet,
TouchableOpacity,
Image
} from 'react-native';
import Pie from 'react-native-pie';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import NaviBarView from './../Commons/NaviBar'
import actions from '../../Redux/actions'
class Main extends Component {
constructor(props){
super(props);
this.state={
cargando:true,
cryptoCurrencyValues:{}
}
this.onNextPress = this.onNextPress.bind(this);
this.renderItems = this.renderItems.bind(this);
}
static getDerivedStateFromProps(nextProps,prevState){
console.warn('Positivo', Object.keys(nextProps.cryptoCurrencyValues).length)
if (Object.keys(nextProps.cryptoCurrencyValues).length !== 0){
}else{
console.warn('Negativo')
}
return null;
}
onNextPress(){
**//HERE I WANT TO CALL NAVIGATE TO MOVE TO ANOTHER SCREEN**
}
componentDidMount(){
console.warn('esto una vez')
this.props.actions.getCryptoValues();
this.setState({cargando:true})
}
renderItems(){
var self = this;
return listData.map(function(cryptoValue,i){
return(
<View style={styles.itemContainer} key={i}>
<View style={{alignSelf:'center',backgroundColor:'transparent', marginLeft:10}}>
<Image source={cryptoValue.img} style={{width:width*0.095, height:height*0.050}} resizeMode={'stretch'}/>
</View>
<View style={{marginLeft:10}}>
<View style={{alignSelf:'flex-start',marginTop:15}}>
<Text style={{color:'#ffffff',fontSize:18,fontWeight: 'bold'}}>{cryptoValue.name}</Text>
</View>
<View style={{alignSelf:'flex-start',marginBottom:10}}>
<Text style={{color:'#6e6e6e',fontSize:18}}>{cryptoValue.desc}</Text>
</View>
</View>
<View style={{marginLeft:40}}>
<View style={{alignSelf:'flex-start',marginTop:15}}>
<Text style={{color:'#ffffff',fontSize:18}}>{cryptoValue.price}</Text>
</View>
<View style={{alignSelf:'flex-start',marginBottom:10}}>
<Text style={{color:'#6e6e6e',fontSize:18}}>{cryptoValue.currency}</Text>
</View>
</View>
<View style={{alignSelf:'center',backgroundColor:'transparent', marginLeft:50}}>
<TouchableOpacity onPress={() => self.onNextPress()} style={{alignSelf:'center',backgroundColor:'transparent'}}>
<Image source={require('./../../img/next.png')} style={{width:width*0.035, height:height*0.032}} resizeMode={'stretch'}/>
</TouchableOpacity>
</View>
</View>
);
});
}
render(){
return(
<View style={styles.container}>
<View>
<NaviBarView/>
</View>
<View style={styles.cardContainer}>
<View style={{marginTop:10,flexDirection: 'row',marginTop:10,marginLeft:10,alignItems:'stretch'}}>
<Image source={require('./../../img/pie-chart.png')} resizeMode={'stretch'} style={{width:width*0.095, height:height*0.055}}/>
<Text style={{fontSize:20,color:'#ffffff',fontWeight:'bold',marginLeft:15,alignSelf:'center'}}>STATUS</Text>
<TouchableOpacity style={{marginLeft:230,alignSelf:'center'}}>
<Image source={require('./../../img/reload.png')} resizeMode={'stretch'} style={{width:width*0.065, height:height*0.035}}/>
</TouchableOpacity>
</View>
<View style={{alignSelf:'flex-start',marginTop:50}}>
<Pie
radius={100}
innerRadius={97}
series={[10, 20, 30, 40]}
colors={['#f00', '#0f0', '#00f', '#ff0']}
/>
</View>
</View>
{this.renderItems()}
</View>
);
}
}
const listData = [
{_id:1,name:'Bitcoin',desc:'Billetera BTC',price:'$141,403.22',currency:'BTC: $11.673,50',img:require('./../../img/bitcoin.png')},
{_id:2,name:'Ethereum',desc:'Billetera ETH',price:'$20200,50',currency:'ETH: $863,40',img:require('./../../img/ethereum.png')},
{_id:3,name:'NEO',desc:'Billetera NEO',price:'$40.401',currency:'NEO: $118,02',img:require('./../../img/neo.png')},
];
const styles = new StyleSheet.create({
container:{
flex:1,
backgroundColor: '#0d0d0d',
flexDirection: 'column',
position:'relative',
},
cardContainer:{
backgroundColor:'#1a1a1a',
marginTop: 7,
marginBottom:7,
marginLeft:7,
marginRight:7,
height:height*0.50,
width:width,
justifyContent: 'flex-start'
},
itemContainer:{
flexDirection: 'row',
backgroundColor:'#1a1a1a',
width:width,
height:height*0.115,
marginLeft:7,
marginRight:7,
marginBottom:7,
justifyContent: 'flex-start'
},
})
function mapStateToProps (state,props) {
return {cryptoCurrencyValues: state.cryptocurrencyValues,
}
}
function mapDispatchToProps (dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Main);
You can use Stack Navigator here which is very easy to navigate from one screen to another and as well as in function too...
First.
Install library :-
npm install --save react-navigation
Then use it in your class by using import :-
import {StackNavigator} from 'react-navigation';
export that class
export default Project = StackNavigator(
{
xyz: { screen: xyz },
});
After that navigating using function:-
onNextPress=()=>
{
this.props.navigation.navigate('xyz');
}
Hope.it will helps you .
Thanx!
I was not passing the navigation prop when defining my RootStack:
import React, {Component} from 'react'
import {
AppRegistry,
StyleSheet,
Text,
View,
} from 'react-native';
import createStore from './../../Redux/store';
import {StackNavigator} from 'react-navigation';
import { Provider } from 'react-redux';
import MainView from '../Main/Main';
import MainSecondLvlView from '../Main/MainSecondLvl';
import BalanceView from './../Charts/BalanceView'
import MenuView from './Menu'
const store = createStore();
const RootStack = StackNavigator({
Main: { screen: MainView },
MainSecondLvl: { screen: MainSecondLvlView},
Menu:{ screen: MenuView }
},
{
initialRouteName: 'Main',
headerMode: 'none',
});
export default class App extends Component {
render(){
return(
<Provider store={store}>
<RootStack navigation={this.props.navigation}/>
</Provider>
);
}
}

Categories

Resources