Is it possible to load particular screen in react native without navigation - react-native

I am using react native 0.64, I want to load my profile screen from home screen without using navigation. Is it possible? Can anyone help?

You should use a state for represent home or profile.
for ex:
function HomeScreen() {
const [screenName, setScreenName] = useState('home')
if (screenName == 'profile') {
return <ProfileScreen/>
}
return {
...
// handling the event to go Profile screen
setScreenName('profile')
...
}
}

Related

Fetching Data From Server Using iOS Device in React Native

I have just started learning React Native and development for mobile devices. One of the things I've tried is using fetch API to get data from http://jsonplaceholder.typicode.com/posts
The App.js file is given below:
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
export default function App() {
const [firstLoad, setLoad] = React.useState(true);
const [data, upDateData] = React.useState([]);
let isLoading = true;
async function sampleFunc() {
let response = await fetch("https://jsonplaceholder.typicode.com/posts");
let body = await response.json();
upDateData(body);
}
if (firstLoad) {
sampleFunc();
setLoad(false);
}
if (data.length > 0) isLoading = false;
const posts = data.map(post => (
<div>
<h1>{post.title}</h1>
<p>{post.body}</p>
</div>
));
return (
<View style={styles.container}>
{isLoading ?
<Text>Loading</Text> :
<Text>{posts}</Text>
}
</View>
);
}
Nothing fancy is going on here, just making an https request to the server to get posts. While the data is being transferred, the Loading label is being displayed, after that, all fetched posts are rendered on the page.
I am using Expo, and everything works fine when I run it in the browser, but when I scan the QR code, Expo app opens, the Loading message is displayed for a couple of seconds, and then the app crashes.
I may be doing something here that is typical of regular React and is not used in React Native. It is just strange that it would work on my computer and not the phone. Any suggestions would be greatly appreciated. Thank you in advance!
You cannot have text outside of Text components in react-native.
In your example, in the post function, you use the h1 and p tags, which are not supported by react-native.
The fix here is to make sure that those texts are inside Text components, you can have styling set to those to make them look closer to what you want.
You can refer the docs on how to create custom styles.
const posts = data.map(post => (
<View>
<Text>{post.title}</Text>
<Text>{post.body}</Text>
</View>
));
To debug similar issues in the future, you should be getting a red flashing screen with the exception. (Maybe it doesn't appear when running on Expo)

How to get current routes size of wix/react-native-navigation?

I'm trying to handle the back button on android since my React Native app has custom logic on the back button pressed for the root screen...Is there any method like Navigation.getCurrentRoutes()
in order to do something like this:
handleBackButton = () => {
if(Navigation.getCurrentRoutes().size()>1) {
return true; // addEventListener listens for the native hardware back button press and will ignore it
}
... customLogic
return false; // will execute the native back press (and exit the app)
}
"react-native-navigation": "3.0.0-alpha.2"
It turns out that there is not such a method and the two options are:
1) Handle back buttons on your own (overriding) or
2) just add your custom logic into componentWillUnmount() and continue using the native react-native-navigation
options 2 worked for me
reference: https://github.com/wix/react-native-navigation/pull/4226#issuecomment-433683885
https://github.com/wix/react-native-navigation/issues/4231

Localization of React Native navigators

I am building an app where the users are prompted to choose their language the first time they launch the app. The language is then stored locally using AsyncStorage.
Every time the app launches the language is retrieved from storage and saved into the global.lang variable to be used by all components:
AsyncStorage.getItem('settings', (err, item) => {
global.lang = item.lang;
});
When I use the global.lang variable in the render() method in any component everything seems to be ok. However I run into trouble when trying to use the same variable when initializing my navigators:
const TabNavigator = createBottomTabNavigator(
{
Home: {
screen: HomeScreenNavigator,
navigationOptions:{
title: strings['en'].linkHome, --> this works
}
},
News: {
screen: NewsScreen,
navigationOptions:{
title: strings[global.lang].linkNews, --> this fails
}
}
});
I believe that this because the value is not retrieved from AsyncStorage by the time that the navigators are constructed. If I set the global.lang manually (eg. global.lang = 'en';) it seems to be OK, but not when I try to retrieve it from the storage.
Is there something that I am missing? Could I initialize the navigator with a default language and change the title later based on the value retrived?
Any help would be greatly appreciated.
The navigators are constructed in the app launch. So you would need to use some placeholder text and use the method described here where you change all screen titles based on the screen key...
Or... this sounds insane and i have never tried it. But you can use a loading screen where you retrieve the languaje settings. then... via conditional rendering you "render" a navigator component . Idk if it would work the same way , but you can try it. below some code that i just created for this purpose
export default class MainComponent extends React.Component {
constructor(props) {
super(props);
this.state = { hasLanguage:false};}
componentDidMount(){
this.retrieveLanguage()
}
async retrieveLanguage(){
//await AsyncStorage bla bla bla
//then
this.setState({hasLanguage:true})
}
render() {
return (
{
this.state.hasLanguage?
<View>
//this is a view that is rendered as a loading screen
</View>:
<Navigator/>//this will be rendered, and hence, created, when there is a language retrieved
}
);
}
}
Again. I don't know if react navigation creates the navigator at render . If so. When it creates a navigator , there should be the languaje to be used there

How to pass data from one view to another view in react native?

I want to pass one array from first view to second view in react native. So how can I achieve this in react native ? For navigation I am using 'react-navigation'.
this.navigation.navigateWithDebounce('BlaBlaView', {title: 'BlaBla View'}).
If your'e using react-navigation's naviagte. you can pass the parameters as the second parameter, for instance:
this.props.navigation.navigate(`ROUTE_NAME`, { params: 'param value' });
And then, within the view you navigated to you can access it:
componentWillMount() {
const { param } = this.props.navigation.state.params;
}

Rendering Components runtime during the navigation in react-native

I want to display a component(say, a View or Text component) in my current screen only if I return back to this screen from some other screen.
For e.g, say I am at the Home.js where I am displaying the view components. The count of this view components depends upon the number of times one goes(or visits) the Break.js screen. Like If i have visited the Break.js screen thrice, then there should be 3 View components available at the Home.js screen.
I am a beginner in React-Native, so don't have any idea how to implement this....I have gone through the similar query like
Dynamically rendering components - React Native and
React Native View Render
but couldn't understand anything. Pls help as I have nothing to show what I have tried so far.....
Below is one way of updating your component, where you update the viewCount before navigating to the other screen. This works only if the previous screen exists in the memory after navigation like in the cases of stack navigators. This is a basic idea which u can modify for your use case.
class HomeScreen extends Component {
onNavigate() {
this.updateViewCount();
// ... navigate to BreakScreen
}
updateViewCount() {
this.setState({numOfViews: this.state.numOfViews + 1});
}
render() {
// Create an array and push your elements based on count
// this.state.numOfViews manages the count
let views = [];
for(let i = 0; i <= this.state.numOfViews; i++) {
views.push(<SomeComponent />);
}
// Render your custom views
return(
<View>
{views}
<Button onPress={() => this.onNavigate()} />
</View>
);
}
}