I'm new to react native and in my sample app I can't handle properly results returned from ImagePicker of this component https://github.com/react-native-image-picker/react-native-image-picker
I'm running react 0.65 and below is my code:
import * as ImagePicker from 'react-native-image-picker';
export class App extends Component {
constructor() {
super();
this.state = { imageSource: null };
}
selectImage = () => {
const selectImageFromGallery = async () => {
const response = await ImagePicker.launchImageLibrary('library', {
selectionLimit: 1,
mediaType: 'photo',
includeBase64: true,
});
const {img64base} = response.assets[0];
this.setState({img64base});
};
selectImageFromGallery();
// console.log(resp);
}
render() {
return (
<SafeAreaView style={{justifyContent: 'center', alignItems: 'center'}}>
<Button title='Select from gallery' onPress={() => this.selectImage()} />
<Image source={this.state.imageSource} />
</SafeAreaView>
);
};
}
Upon run of application I can press button and select image, but whenever I confirm my selection it is throwing error in console and on the screen of Android device:
Uncaught Error:
'Type Error: callback is not a function'
This call stack is not sybmolicated.
I do understand that I miss to handle correctly promise or callback but I cant figure out correct syntax. Could you please help? Tried zillion of times with 'await', without await, etc. The only thing I need to stay with component class and I won't change to function class - have single calls in componentDidMount functions to make sure some specific hardware is called only once. Pease help
selectImage = async () {
const response = await ImagePicker.launchImageLibrary('library', {
selectionLimit: 1,
mediaType: 'photo',
includeBase64: true,
});
const {img64base} = response.assets[0];
this.setState({img64base});
}
import { View, ScrollView, StyleSheet } from 'react-native'
import Heading from './Heading'
import Input from './Input'
class App extends Component {
constructor () {
super()
this.state = {
input value: '',
todos: [],
type: 'All'
}
inputChange (inputValue) {
this.setState({inputValue})
}
}
render () {
const {todos, inputValue, type } = this.state
return (
<View style={styles.container}>
<ScrollView keyboardShouldPersistTaps='always'
style={styles.content}>
<Heading />
<Input
input Value={inputValue}
inputChange={(text) => this.inputChange(text)} />
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create ({
container: {
flex: 1,
backgroundColor: '#f5f5f5'
},
content: {
flex: 1,
paddingTop: 60
}
})
export default App
"So I have this error that I have tried to fix through disabled eslint and it's not working. This is my first time using react-native. I'm taking a class and this is for an assignment of mine to create a TodoApp. My teacher gave us the exact code he wanted us to input into VSCode, so we could then make changes to it accordingly for the assignment. I was halfway through his video, and this error kept coming up, but not for him. I have looked all around for an answer and can't seem to find one. The section of code that gives me a problem in the inputChange (inputValue) and say it's missing a semicolon. In the video the teacher doesn't put one and it works completely fine. I've done some reading that it could be eslint, but I've tried to disable it and it still doesn't work."
With this code, you are attempting to define the method inputChange inside the constructor method, which is not possible. You need to close the constructor method definition before defining your inputChange method. I recommend taking a closer look at the code your instructor provided. I suspect that on closer inspection you will find one curly brace closing the setState function and another curly brace closing the constructor method before that inputChange method definition starts.
change position of inputChange function from inside of constructor to body of class ( after closing constructor )
class App extends Component {
constructor() {
// ...
}
inputChange(inputValue) {
// ...
}
render() {
return (
<>{/* rest of code */}</>
);
}
}
Edit
you may name properties incorrect
I am trying to validate a text field on click of Submit button. But I always get the error -
TypeError: undefined is not an object (evaluating 'props.deviceLocale') on my emulator.
(I am using an Android emulator).
However I am nowhere using 'deviceLocale' in my code. I am not aware if it is required for anything I have in my code.
This is my code:
import React, {Component} from 'react';
import { View, Text, TouchableOpacity, TextInput } from 'react-native';
import ValidationComponent from 'react-native-form-validator';
export default class App extends ValidationComponent {
constructor() {
super()
this.state = {
name: "abc"
}
}
_onPressButton() {
this.validate({
name: {minlength: 3, maxlength: 7, required: true},
});
}
render() {
return (
<View>
<TextInput
ref = "name"
onChangeText = {(name) => this.setState({name})}
value = {this.state.name}
/>
<TouchableOpacity onPress = {this._onPressButton}>
<Text>Submit</Text>
</TouchableOpacity>
</View>
)
}
}
Error snap:
You are getting the error even before loading of the component then, do bind your _onPressButton correctly, then atleast your component will get mounted properly, then then your upcoming errors will follow like the use of this.validate is somewhat ambiguous to me as I cannot see validate function in the component.
To bind your _onPressed, declare it like below:
_onPressButton = () => {
this.validate({
name: {minlength: 3, maxlength: 7, required: true},
});
}
The error is causing as _onPressed is getting called as soon as your component is getting mounted. Let me know in comments if this helps you getting ahead with your component mounting atleast.
Edited:
Also, your constructor doesn't provide props to the super constructor,
Declare it like below:
constructor(props) {
super(props);
this.state = {
name: "abc"
}
}
I'm developing an app with React Native and I'm testing with my OnePlus 6 and it has a notch. The SafeAreaView is a solution for the iPhone X but for Android, it seems there is no solution.
How to solve this kind of issue?
Do something like
import { StyleSheet, Platform, StatusBar } from "react-native";
export default StyleSheet.create({
AndroidSafeArea: {
flex: 1,
backgroundColor: "white",
paddingTop: Platform.OS === "android" ? StatusBar.currentHeight : 0
}
});
And then In your App.js
import SafeViewAndroid from "./components/SafeViewAndroid";
<SafeAreaView style={SafeViewAndroid.AndroidSafeArea}>
<Layout screenProps={{ navigation: this.props.navigation }} /> //OR whatever you want to render
</SafeAreaView>
This should work good as get height will take care of the knotch in android device by calculating the statusBar height and it will arrange accordingly.
A work around I had to use recently:
GlobalStyles.js:
import { StyleSheet, Platform } from 'react-native';
export default StyleSheet.create({
droidSafeArea: {
flex: 1,
backgroundColor: npLBlue,
paddingTop: Platform.OS === 'android' ? 25 : 0
},
});
It is applied like so:
App.js
import GlobalStyles from './GlobalStyles';
import { SafeAreaView } from "react-native";
render() {
return (
<SafeAreaView style={GlobalStyles.droidSafeArea}>
//More controls and such
</SafeAreaView>
);
}
}
You'll probably need to adjust it a bit to fit whatever screen you're working on, but this got my header just below the icon strip at the top.
Late 2020 answer: For anyone stumbling across this issue themselves, they have added support for this.
Follow this documentation page
You could also create helper component with this style applied right away like this
import React from 'react';
import { StyleSheet, Platform, StatusBar, SafeAreaView } from 'react-native';
export default props => (
<SafeAreaView style={styles.AndroidSafeArea} {...props} >
{props.children}
</SafeAreaView>
);
const styles = StyleSheet.create({
AndroidSafeArea: {
paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0
}
});
Make note that I also deleted unnecessary styles which breaks natural behavior of SafeAreaView which in my case broke styling.
As for use you simply use it like normal SafeAreaView:
import React from 'react';
import SafeAreaView from "src/Components/SafeAreaView";
render() {
return (
<SafeAreaView>
// Rest of your app
</SafeAreaView>
);
}
}
for more consistency import:
import { Platform, StatusBar } from "react-native";
and then use it like so:
paddingTop: Platform.OS === 'android' ? StatusBar.currentHeight : 0
if you're seeing this in 2020 and you also need the web support with the Android and iOS, type this in your terminal.
expo install react-native-safe-area-context
this will install the updated safe area context.
Then import the following stuffs into your app.js
import { SafeAreaView, SafeAreaProvider} from "react-native-safe-area-context";
add <SafeAreaProvider> before all the tags in your main function in app.js, also remember to close it at the end.
and finally, instead of view, add SafeAreaView.
Read more at the official expo website : SafeAreaContext
Although the docs says it is relevant only for iOS, when I used React's SafeAreaView it acted differently on different screens on Android.
I managed to fix the problem by implementing my version of SafeAreaView:
import React from "react";
import { Platform, View, StatusBar } from "react-native";
import { GeneralStyle } from "../styles";
export function SaferAreaView({ children }) {
if (Platform.OS == "ios") {
return <SaferAreaView style={{ flex: 1 }}>{children}</SaferAreaView>;
}
if (Platform.OS == "android") {
return <View style={{flex: 1, paddingTop: StatusBar.currentHeight}}>{children}</View>;
}
}
This was tested on an old device (with hardware navigation) and new notch devices (with software navigation) - different screen sizes.
This is currently the best or easiest way to implement SafeAreaView on Android and ios for both vanilla RN and Expo.
import { SafeAreaView } from 'react-native-safe-area-context';
function SomeComponent() {
return (
<SafeAreaView>
<View />
</SafeAreaView>
);
}
1 - expo install expo-constants
2- and do like this for example
import React from "react";
import Constants from "expo-constants";
import { Text, StyleSheet, SafeAreaView, View } from "react-native";
export default function HeaderTabs({ style }) {
return (
<SafeAreaView style={[styles.screen, style]}>
<View style={[styles.view, style]}>
<Text>Hello this is status bar</Text>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
screen: {
paddingTop: Constants.statusBarHeight,
flex: 1,
},
view: {
flex: 1,
},
});
Instead of using Platform API, you can use expo constants.
npm i expo-constants
then import it in your component as
import Constants from "expo-constants"
and then in the styles you can use it like this
const styles = StyleSheet.create({
container: {
paddingTop: Constants.statusBarHeight
} });
To see all the properties of Constants console log it you will find some more useful things.
Well, I had the same problem. I solved this using this lib React Native Status Bar Height, and I recommend because it´s a piece of cake to use.
And if you are using style-components you can add the getStatusBarHeight() on your styles.js like I did on the example below:
import styled from 'styled-components/native';
import { getStatusBarHeight} from 'react-native-status-bar-height';
export const Background = styled.View`
flex:1;
background:#131313;
margin-top: ${getStatusBarHeight()};
`
In the SafeAreaView Docs was told:
It is currently only applicable to iOS devices with iOS version 11 or later.
So now I definitely use it in my project but I use Platform to recognize device platform and for Android, I make a manual safe area for the status bar.
you can use react-native-device-info for device info and apply styling also with a notch
I used StatusBar from react-native instead of expo-status-bar and this worked for me on my OnePlus as well as other Android devices.
import { StatusBar } from 'react-native';
Expo solution(docs - android only):
import { setStatusBarTranslucent } from 'expo-status-bar';
Then in the component you can use useEffect hook:
useEffect(() => {
setStatusBarTranslucent(false)
},[])
for iOS you can use the <SafeAreaView> component from react-native.
ENRICO SECCO was right (i cant comment due to my stackoverflow reputation lol)! any safeareaview thingy doesn't work for me as well, so i get around with
import { getStatusBarHeight} from 'react-native-status-bar-height';
here how execute it, keep in mind that this is in my app.js, where i put all my stack.navigator + bottomtab.navigator
export default function App() {
//IGNORE ALL OF THIS, JUMP TO THE RETURN() FUNCTION!
const [appIsReady, setAppIsReady] = useState(false);
useEffect(() => {
async function prepare() {
try {
await SplashScreen.preventAutoHideAsync();
await Font.loadAsync(AntDesign.font);
await Font.loadAsync({
'Montserrat-Bold': require('./assets/fonts/Montserrat-Bold.ttf'),
'Montserrat-Regular': require('./assets/fonts/Montserrat-Regular.ttf'),
'Montserrat-Light': require('./assets/fonts/Montserrat-Light.ttf'),
});
await new Promise(resolve => setTimeout(resolve, 2000));
} catch (e) {
console.warn(e);
} finally {
// Tell the application to render
setAppIsReady(true);
}
}
prepare();
}, []);
const onLayoutRootView = useCallback(async () => {
if (appIsReady) {
await SplashScreen.hideAsync();
}
}, [appIsReady]);
if (!appIsReady) {
return null;
}
return (
//HERE!
<NavigationContainer>
<View style = {{
flex: 1, <- TO MAKE IT FULL SCREEN (PLEASE DELETE THIS)
marginTop: getStatusBarHeight(), <- TO PUSH IT DOWN FROM OFF SCREEN, MINE RAN OFF TO THE TOP LMAO (PLEASE DELETE THIS)
}} onLayout={onLayoutRootView}>
<Tabs/>
</View>
</NavigationContainer>
);
}
This is possibly just an Android 6.0 bug. I tested the snack below in Android 5.1.1 and Android 7.0 and it didn't happen there.
I am trying to do an autocomplete whenever the user types "#". I successfully do this, however once I backspace a couple times, the value on the native side becomes some value I never had before. I have simplified the case to this code below:
Please try the snack here - https://snack.expo.io/#noitsnack/what-the-heck---autocomplete-then-backspace-bug OR copy and paste the code into a new react-native init project. I tested in RN 0.51 and RN 0.54.
Please then type Hi #
You will see it autocompletes to Hi #foobar.
Then backspace once and it properly is now Hi #fooba.
Backspace again, and now it is Hi #foHi (this is the bug, it should be Hi #foob)
This is a controlled input. I have no idea why it's turning into Hi #foHi on second backspace. If I blur then come after step 3 it doesn't come back.
I tried on two other devices, Android 7.0 and Android 5.1.1, and this bug was not there. It only happened on my Android 6.0. I think this is a OS dependent bug. Does anyone have ideas on what is actually going on? That will help me on how to work around this on all devices.
Is this really a bug on RN side?
I recorded a screencast of this behavior here in HD:
https://gfycat.com/RectangularAltruisticEuropeanfiresalamander
Here is a GIF:
The code (copied from the expo snack):
import React, { Component } from 'react';
import { StyleSheet, Text, View, TextInput } from 'react-native'
class FieldMentionable extends Component<Props, State> {
state = {
value: ''
}
render() {
const { value } = this.state;
return <TextInput onChange={this.handleChange} value={value} multiline />
}
handleChange = ({ nativeEvent:{ text }}) => {
const { value } = this.state;
if (text.endsWith(' #')) this.setState(() => ({ value:text + 'foobar' }));
else this.setState(() => ({ value:text }));
}
handleRef = el => this.input = el;
}
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<FieldMentionable />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
paddingHorizontal: 100,
backgroundColor: '#F5FCFF',
}
});
This is a bug on and its root issue has been filed here - https://github.com/facebook/react-native/issues/19085