hi my dear friends i have problem in my simple code in react native
when i run the code i` giving this error. apologize i'm nub in react native :)
import React, { Component } from 'react';
import {
ListView,
View
} from 'react-native';
import MyPresentationalComponent1 from './MyPresentationalComponent1'
export default class MyContainerComponent extends Component {
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !==
r2});
this.state = {
dataSource: ds.cloneWithRows([
'Item1', 'Item2', 'Item3', 'Item4', 'Item5', 'Item6', 'Item7',
'Item8',
'Item9', 'Item10'
])
};
}
render() {
return (
<View>
<MyPresentationalComponent1 dataSource = {this.state.dataSource}/>
</View>
);
}
}`
Related
I have created my app with Expo(React Navigation 5.0) and changed "createBottomTabNavigator" to "createMaterialBottomTabNavigator". But When it is at front as soon as it was at back, it is blink.
This is the captured screen of terminal for my initiating app.
creating my app by EXPO
This is the code which is only changed by me.
import { createMaterialBottomTabNavigator } from '#react-navigation/material-bottom-tabs';
const BottomTab = createMaterialBottomTabNavigator<BottomTabParamList>();
The rest of code is automatically made by "expo init my-app"
This is App.tsx
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import useCachedResources from './hooks/useCachedResources';
import useColorScheme from './hooks/useColorScheme';
import Navigation from './navigation';
export default function App() {
const isLoadingComplete = useCachedResources();
const colorScheme = useColorScheme();
if (!isLoadingComplete) {
return null;
} else {
return (
<SafeAreaProvider>
<Navigation colorScheme={colorScheme} />
<StatusBar />
</SafeAreaProvider>
);
}
}
and this is index.tsx
import { NavigationContainer, DefaultTheme, DarkTheme } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import * as React from 'react';
import { ColorSchemeName } from 'react-native';
import NotFoundScreen from '../screens/NotFoundScreen';
import { RootStackParamList } from '../types';
import BottomTabNavigator from './BottomTabNavigator';
import LinkingConfiguration from './LinkingConfiguration';
// If you are not familiar with React Navigation, we recommend going through the
// "Fundamentals" guide: https://reactnavigation.org/docs/getting-started
export default function Navigation({ colorScheme }: { colorScheme: ColorSchemeName }) {
return (
<NavigationContainer
linking={LinkingConfiguration}
theme={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
<RootNavigator />
</NavigationContainer>
);
}
// A root stack navigator is often used for displaying modals on top of all other content
// Read more here: https://reactnavigation.org/docs/modal
const Stack = createStackNavigator<RootStackParamList>();
function RootNavigator() {
return (
<Stack.Navigator screenOptions={{ headerShown: false }}>
<Stack.Screen name="Root" component={BottomTabNavigator} />
<Stack.Screen name="NotFound" component={NotFoundScreen} options={{ title: 'Oops!' }} />
</Stack.Navigator>
);
}
This is blinking captured video
I hope anyone can help me
It is a known bug in react-native.
https://github.com/facebook/react-native/issues/28525
Try to replace useColorScheme hook (hooks/useColorScheme.ts) with the following code:
import { Appearance, ColorSchemeName } from 'react-native';
import { useEffect, useRef, useState } from 'react';
export default function useColorScheme(delay = 500): NonNullable<ColorSchemeName> {
const [colorScheme, setColorScheme] = useState(Appearance.getColorScheme());
let timeout = useRef<NodeJS.Timeout | null>(null).current;
useEffect(() => {
Appearance.addChangeListener(onColorSchemeChange);
return () => {
resetCurrentTimeout();
Appearance.removeChangeListener(onColorSchemeChange);
};
}, []);
function onColorSchemeChange(preferences: Appearance.AppearancePreferences) {
resetCurrentTimeout();
timeout = setTimeout(() => {
setColorScheme(preferences.colorScheme);
}, delay);
}
function resetCurrentTimeout() {
if (timeout) {
clearTimeout(timeout);
}
}
return colorScheme as NonNullable<ColorSchemeName>;
}
Hi all i want to try implement react-native-dark-mode but not worked in my project.
"react-native": "0.61.5"
I Already try like this :
import { useDarkMode } from 'react-native-dark-mode'
export default class Login extends Component {
render(){
const isDarkMode = useDarkMode() // i think this make error
return(
<View style={{ backgroundColor: isDarkMode ? 'black' : 'white' }}></View>
)
}
}
This my error
error-output
any solutions?
In your scenario react hooks can only be used inside the functional components
Example of functional component usage:
import { useDarkMode } from 'react-native-dark-mode'
function Component() {
const isDarkMode = useDarkMode()
return <View style={{ backgroundColor: isDarkMode ? 'black' : 'white' }} />
}
Example of class component usage:
You can play around with DarkModeContext. Just make sure to wrap your application in a DarkModeProvider with no props to avoid getting a value of current.
1 - Setup context provider for the app.
// App.js or top of the hierarchy in your app
import React, {Component} from 'react';
import {DarkModeProvider} from 'react-native-dark-mode';
export default class App extends Component {
render() {
return (
<DarkModeProvider>
<YourApp />
</DarkModeProvider>
);
}
}
2 - Use the context with contextType or context consumer.
// class based component with contextType
import React, {Component} from 'react';
import {Text} from 'react-native';
import {DarkModeContext} from 'react-native-dark-mode';
export default class HelloWorldText extends Component {
static contextType = DarkModeContext;
render() {
const isDarkMode = this.context === 'dark';
return (
<Text style={{color: isDarkMode ? '#ffffff' : '#000000'}}>
{this.props.children}
</Text>
);
}
}
3 - Final class based component
// class based component with context consumer
import React, {Component} from 'react';
import {Text} from 'react-native';
import {DarkModeContext} from 'react-native-dark-mode';
export default class HelloWorldText extends Component {
render() {
return (
<DarkModeContext.Consumer>
{mode => (
<Text style={{color: mode === 'dark' ? '#ffffff' : '#000000'}}>
{this.props.children}
</Text>
)}
</DarkModeContext.Consumer>
);
}
}
If you want to know about the context, you can find more detail in context page. It is really useful feature for both, class and function components.
So i am new to react native and JS in general, i have a huge background in native mobile development and i want to know more about Web Apps. So i try to begin with react native to experience that.
I wanted to do a side menu using createDrawerNavigator, so i created the following component :
// code for the menu
import React from 'react';
import { Platform } from 'react-native';
import { createStackNavigator, createDrawerNavigator, createAppContainer, DrawerActions } from "react-navigation";
import HomeScreen from '../screens/HomeScreen';
import LinksScreen from '../screens/LinksScreen';
import SettingsScreen from '../screens/SettingsScreen';
const App = createDrawerNavigator({
HomeScreen: {
screen: HomeScreen
},
LinksScreen: {
screen: LinksScreen
},
SettingsScreen: {
screen: SettingsScreen
}
},
{
drawerWidth: 300
});
export default createAppContainer(App);
// HomeScreen.js
import React from 'react';
import {
Image,
Platform,
ScrollView,
StyleSheet,
Text,
TouchableOpacity,
View,
Dimensions,
} from 'react-native';
import { WebBrowser } from 'expo';
import { DrawerNavigator } from 'react-native-navigation';
import { MonoText } from '../components/StyledText';
import { createStackNavigator, createDrawerNavigator, createAppContainer, DrawerActions } from "react-navigation";
import Router from './MenuNavigator';
export default class HomeScreen extends React.Component {
static navigationOptions = {
header: 'Vapeself 2',
};
render() {
const App = createDrawerNavigator({
Home: {
screen: MyHomeScreen,
},
Notifications: {
screen: MyNotificationsScreen,
},
});
const MyApp = createAppContainer(App);
this.props.navigation.dispatch(DrawerActions.openDrawer());
return (
<Router/>
);
}
// LinkScreen.js
import React from 'react';
import { ScrollView, StyleSheet } from 'react-native';
import { ExpoLinksView } from '#expo/samples';
export default class LinksScreen extends React.Component {
static navigationOptions = {
title: 'Links',
};
render() {
return (
<ScrollView style={styles.container}>
{/* Go ahead and delete ExpoLinksView and replace it with your
* content, we just wanted to provide you with some helpful links */}
<ExpoLinksView />
</ScrollView>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 15,
backgroundColor: '#fff',
},
});
// SettingsScreen.js
import React from 'react';
import { ExpoConfigView } from '#expo/samples';
export default class SettingsScreen extends React.Component {
static navigationOptions = {
title: 'app.json',
};
render() {
/* Go ahead and delete ExpoConfigView and replace it with your
* content, we just wanted to give you a quick view of your config */
return <ExpoConfigView />;
}
}
I don't know what happened because the code doesn't work, and i have this kind of error The component for route 'HomeScreen' must be a React component . But the thing is that its actually work with a TabNavigator. So i really don't understand.
Thank you in advance for the help.
I am new to React Native and trying to create a simple iOS app. The app has a button on clicking which I need to store the timestamp of the click on the device in a file.
I know that React Native has an API called AsyncStorage but I am getting errors while using this. I copied the code from some site on the net.
Can someone please guide me to use this API?
This is my entire code:
import React, {Component} from 'react';
import { StyleSheet, Text, View, TextInput, AsyncStorage } from 'react-native';
export default class App extends Component{
state = {
'name': ''
}
componentDidMount = () => AsyncStorage.getItem('name').then((value) => this.setState({'name': value}))
setName = (value) => {
AsyncStorage.setItem('name': value);
this.setState({'name': value});
}
render() {
return (
<View style={styles.container}>
<TextInput style = {styles.textInput} autoCapitalize = 'none'
onChangeText = {this.setName}/>
<Text>
{this.state.name}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
marginTop: 50
},
textInput: {
margin: 15,
height: 35,
borderWidth: 1,
backgroundColor: '#7685ed'
}
});
As for the error, when I launch the code on iOS, I am getting a red screen. There is no syntax error that I can see.
Thanks in advance.
Hard to say without more detail the exact problem you're facing, but I assume some of the following might help you?
Ah I see you posted some code. You will need a constructor that defines your state as well. Added it in my code below.
Please note I'm not an expert. Forgive any errors
import {
AsyncStorage,
} from 'react-native';
class myComponent extends React.Component{
constructor(props) {
super(props);
this.state = {
data: null
};
}
componentDidMount() {
this._loadInitialState().done();
}
_someFunction() {
var myData = 123;
saveItemLocally('data', myData);
}
async _loadInitialState() {
try {
// get localy stored data
var dataStored = await AsyncStorage.getItem('data');
if (dataStored!==null) {
this.setState({
data: dataStored
});
}
} catch (error) {
//didn't get locally stored data
console.log(error.message);
}
} // end _loadinitialstate
render () {
//your render function
return (
);
}
} // end of your component
async function saveItemLocally(item, value) {
try {
await AsyncStorage.setItem(item, value);
} catch (error) {
console.log('AsyncStorage error: ' + error.message);
}
}
I simply want to print a couple of arrays on screen in my React Native iOS app. Right now nothing is showing up on screen. console.logs after the for loop show that the arrays have the data they are supposed to have, but it is not reflected on screen. How do I render again after the fetch call has loaded? Here's my code:
'use unique'
import React, { Component } from 'react';
import {
StyleSheet,
TouchableHighlight,
Text,
View,
ListView
} from 'react-native';
import api from './apicall';
class APIRequest extends Component {
constructor() {
super();
this.state = {
users: [],
id: [],
type: []
}
}
componentWillMount() {
api.getData()
.then((res) => {
this.setState({
users: res
})
for (var i = 0; i < this.state.users.length; i++) {
this.state.id.push(this.state.users[i].id);
this.state.type.push(this.state.users[i].type);
});
}
render() {
return(
<View style={styles.container}>
<Text style={styles.buttonText}>
{this.state.id}
</Text>
</View>
);
}
}
this.state.id.push(this.state.users[i].id);
this.state.type.push(this.state.users[i].type);
That's the wrong way to set new state. You should do the following:
var idArray = [];
var typeArray = [];
for (var i = 0; i < this.state.users.length; i++) {
idArray.push(this.state.users[i].id);
typeArray.push(this.state.users[i].type);
}
this.setState({id: idArray});