How to jump to another view on or before render? - mobile

Below is my index.ios.js and ProfileView.js, I want to navigate to LoginView from within ProfileView immediately if this.state.toContinue is false. I tried to push the view to this.props.navigator but it didn't work :(
// index.ios.js
"use strict";
var React = require("react-native");
var {
AppRegistry,
StyleSheet,
NavigatorIOS,
} = React;
var ProfileView = require('./ProfileView');
var project = React.createClass({
render: function() {
return (
<NavigatorIOS
style={styles.navigationContainer}
initialRoute={{
title: "Your Profile",
component: ProfileView
}}
/>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}
});
AppRegistry.registerComponent("project", () => project);
// ProfileView.js
"use strict";
var React = require('react-native');
var LoginView = require("./LoginView");
var {
Component,
StyleSheet,
View,
} = React;
class ProfileView extends Component {
constructor (props) {
super(props);
this.state = {
toContinue: this.isSignedIn()
};
}
isSignedIn () {
return false;
}
render () {
if (!this.state.toContinue) {
// jump to LoginView
}
return (
<View style={styles.container}>
<Text>
Welcome
</Text>
</View>
);
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}
});
module.exports = ProfileView;
Any help is appreciated!

I'm pretty sure the reason it isn't working is that your "this" reference is being changed from where you want it to be by the if statement you have before it in the render function.
Check out what I have here. It is set up and working.
Note that there are known issues regarding the title in NavigatorIOS not functioning correctly when using .replace, discussed here and here.
The working code is also below:
"use strict";
var React = require("react-native");
var {
AppRegistry,
StyleSheet,
NavigatorIOS,
Component,
StyleSheet,
View,
Text
} = React;
var project = React.createClass({
render: function() {
return (
<NavigatorIOS
style={{flex:1}}
initialRoute={{
component: ProfileView
}}
/>
);
}
});
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}
});
AppRegistry.registerComponent("project", () => project);
// ProfileView.js
"use strict";
var React = require('react-native');
var LoginView = React.createClass({
render: function() {
return(
<View style={{backgroundColor: 'red', flex:1}}>
<Text style={{marginTop:100}}>Hello from LOGIN VIEW</Text>
</View>
)
}
})
class ProfileView extends Component {
constructor (props) {
super(props);
this.state = {
toContinue: this.isSignedIn()
};
}
isSignedIn () {
return false;
}
changeView() {
this.props.navigator.replace({
component: LoginView,
title: 'LoginView',
})
}
componentDidMount() {
if (!this.state.toContinue) {
this.changeView()
}
}
render () {
return (
<View style={styles.container}>
<Text>
Welcome
</Text>
</View>
);
}
};
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
}
});
module.exports = ProfileView;

Related

React Native Webview make back button on android go back

When I click the hardware button on android the app closes, I want to go back on the previous page,
This is my code
import { StatusBar } from 'expo-status-bar';
import React, { useState } from 'react';
import { ActivityIndicator, Linking, SafeAreaView, StyleSheet, Text, View } from 'react-native';
import { WebView } from 'react-native-webview';
export default function App() {
const [isLoadong, setLoading] = useState(false);
return (
<SafeAreaView style={styles.safeArea}>
<WebView
originWhiteList={['*']}
source={{ uri: 'https://google.com' }}
style={styles.container }
onLoadStart={(syntheticEvent) => {
setLoading(true);
}}
onShouldStartLoadWithRequest={(event)=>{
if (event.navigationType === 'click') {
if (!event.url.match(/(google\.com\/*)/) ) {
Linking.openURL(event.url)
return false
}
return true
}else{
return true;
}
}}
onLoadEnd={(syntheticEvent) => {
setLoading(false);
}} />
{isLoadong && (
<ActivityIndicator
color="#234356"
size="large"
style={styles.loading}
/>
)}
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#234356'
},
loading: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
},
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
There are built-in goBack() method available in react-native-webview libraries
you can use the API method to implement back navigation of webview.
For this, you have to get the reference of react-native-webview component and call method from the reference object.
also, you are able to put the listener on the Android Native Back Button Press event to call the goBack() method of webview.
try the following code...
import { StatusBar } from 'expo-status-bar';
import React, { useState, useRef, useEffect } from 'react';
import { ActivityIndicator, Linking, SafeAreaView, StyleSheet, BackHandler } from 'react-native';
import { WebView } from 'react-native-webview';
export default function App() {
const webViewRef = useRef()
const [isLoadong, setLoading] = useState(false);
const handleBackButtonPress = () => {
try {
webViewRef.current?.goBack()
} catch (err) {
console.log("[handleBackButtonPress] Error : ", err.message)
}
}
useEffect(() => {
BackHandler.addEventListener("hardwareBackPress", handleBackButtonPress)
return () => {
BackHandler.removeEventListener("hardwareBackPress", handleBackButtonPress)
};
}, []);
return (
<SafeAreaView style={styles.safeArea}>
<WebView
originWhiteList={['*']}
source={{ uri: 'https://google.com' }}
style={styles.container}
ref={webViewRef}
onLoadStart={(syntheticEvent) => {
setLoading(true);
}}
onShouldStartLoadWithRequest={(event)=>{
if (event.navigationType === 'click') {
if (!event.url.match(/(google\.com\/*)/) ) {
Linking.openURL(event.url)
return false
}
return true
}
else{
return true;
}
}}
onLoadEnd={(syntheticEvent) => {
setLoading(false);
}}
/>
{isLoadong && (
<ActivityIndicator
color="#234356"
size="large"
style={styles.loading}
/>
)}
</SafeAreaView>
);
}
const styles = StyleSheet.create({
safeArea: {
flex: 1,
backgroundColor: '#234356'
},
loading: {
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
alignItems: 'center',
justifyContent: 'center'
},
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
first add ref for access your webview like that:
<WebView
ref={WEBVIEW_REF}
then for access to Hardware Back Button you can use this:
import { BackHandler } from 'react-native';
constructor(props) {
super(props)
this.handleBackButtonClick = this.handleBackButtonClick.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.handleBackButtonClick);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
}
handleBackButtonClick() {
this.refs[WEBVIEW_REF].goBack();
return true;
}
in handleBackButtonClick you can do back for webview and add this.refs[WEBVIEW_REF].goBack(); . I Hope that's helpful:)
Here is a simple solution using the magic of React's State.
Hope this helps.
import React, { useRef, useState } from 'react'
export default function Component () {
// This is used to save the reference of your webview, so you can control it
const webViewRef = useRef(null);
// This state saves whether your WebView can go back
const [webViewcanGoBack, setWebViewcanGoBack] = useState(false);
const goBack = () => {
// Getting the webview reference
const webView = webViewRef.current
if (webViewcanGoBack)
// Do stuff here if your webview can go back
else
// Do stuff here if your webview can't go back
}
return (
<WebView
source={{ uri: `Your URL` }}
ref={webViewRef}
javaScriptEnabled={true}
onLoadProgress={({ nativeEvent }) => {
// This function is called everytime your web view loads a page
// and here we change the state of can go back
setWebViewcanGoBack(nativeEvent.canGoBack)
}}
/>
)
}

Failed to bind EAGLDrawable in WebRTC react native

I'm going to create video chat through webRTC using React native iOS. For that I've written react native code for iOS. It's asking me for camera access but after that it fails to load video and throws a warming message,
Failed to bind EAGLDrawable: <CAEAGLLayer: 0x16d50e30> to GL_RENDERBUFFER 1
Failed to make complete framebuffer object 8cd6
I know above warning is due to not getting view to camera for rendering video frames. But i don't know what wrong with my react code which fails to give it frame, my code is following,
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
View
} from 'react-native';
var WebRTC = require('react-native-webrtc');
var {
RTCPeerConnection,
RTCMediaStream,
RTCIceCandidate,
RTCSessionDescription,
RTCView
} = WebRTC;
var container;
var configuration = {"iceServers": [{"url": "stun:stun.l.google.com:19302"}]};
var pc = new RTCPeerConnection(configuration);
navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
pc.addStream(stream);
});
pc.createOffer(function(desc) {
pc.setLocalDescription(desc, function () {
// Send pc.localDescription to peer
}, function(e) {});
}, function(e) {});
pc.onicecandidate = function (event) {
// send event.candidate to peer
};
var RCTWebRTCDemo = React.createClass({
getInitialState: function() {
return {videoURL: null};
},
componentDidMount: function() {
container = this;
},
render: function() {
return (
<View style={styles.container}>
<RTCView streamURL={this.state.videoURL}/>
</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('RCTWebRTCDemo', () => RCTWebRTCDemo);
I'm interested to know where i'm wrong?
I set frame before
<View style={styles.container}>
<RTCView streamURL={this.state.videoURL}/>
</View>
but its was wrong.
The RTCView creation is slightly different so we set frame inside RTCView syntax. Correct way is,
<View>
<RTCView streamURL={this.state.videoURL} style={styles.container}/>
</View>

Module Error Requiring unknown module

Hello am having a problem I am using react native am a newbie and I am creating a app that has some tabs but what i want is when i click the tab each as its own navigation bar.
I follow [AppCoda Example][1] but i notice that code base is different from the new code base react native. my code is bellow. Remember am trying to get a Nav bar for each tabs an i created a folder structure to require each tab in but am getting that unknown module when i know its there. Just to add if i add the same code which was in sub folder in the index.os.js it works look below:
'use strict';
var React = require('react-native');
var SearchButton = require('./app/components/buttons/searchButton');
var CameraButton = require('./app/components/buttons/cameraButton');
var ProfileButton = require('./app/components/buttons/profileButton');
var ContactButton = require('./app/components/buttons/contactButton');
var {
AppRegistry,
TabBarIOS,
NavigatorIOS,
StyleSheet,
Text,
View
} = React;
class AwesomeProject extends React.Component{
constructor(props) {
super(props);
this.state = {
selectedTab: 'Search'
};
}
render() {
return (
<TabBarIOS selectedTab={this.state.selectedTab} barTintColor="darkslateblue">
<TabBarIOS.Item
selected={this.state.selectedTab === 'Search'}
systemIcon="search"
onPress={() => {
this.setState({
selectedTab: 'Search'
});
}} style={styles.container} >
<SearchButton/>
</TabBarIOS.Item>
<TabBarIOS.Item systemIcon="bookmarks"
selected={this.state.selectedTab === 'Camera'}
icon={{uri:'Camera'}}
onPress={() => {
this.setState({
selectedTab: 'Camera'
});
}}>
<CameraButton/>
</TabBarIOS.Item>
<TabBarIOS.Item systemIcon="history"
selected={this.state.selectedTab === 'Profile'}
icon={{uri:'Profile'}}
onPress={() => {
this.setState({
selectedTab: 'Profile'
});
}}>
<ProfileButton/>
</TabBarIOS.Item>
<TabBarIOS.Item systemIcon="contacts"
selected={this.state.selectedTab === 'Contacts'}
icon={{uri:'Contacts'}}
onPress={() => {
this.setState({
selectedTab: 'Contacts'
});
}}>
<ContactButton/>
</TabBarIOS.Item>
</TabBarIOS>
);
}
};
var styles = StyleSheet.create({
navigator: {
flex: 1,
},
tabContent: {
flex: 1,
alignItems: 'center', },
tabText: {
color: 'white',
margin: 50, },
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);
Now in the search button which should get the search title from a navigation folder thats where the problem is its saying unknown module
'use strict';
var React = require('react-native');
var searchTitle = require('./app/components/navigation/searchTitle');
var {
StyleSheet,
View,
NavigatorIOS,
Text
} = React
var styles = StyleSheet.create({
navigator: {
flex: 1
}
}
);
class Search extends React.Component{
render() {
return (
<NavigatorIOS
style={styles.navigator}
initialRoute={{
title: 'SomeTitle',
component: searchTitle
}}/>
);
}
}
module.exports = Search;
can some one help me with this.
You are asking require to search a relative path. From your examples I see that searchButton is in ./app/components/buttons/ and searchTitle is in ./app/components/navigation/, so if you want to require searchTitle from searchButton the path you need to specify is ../navigation/searchTitle.
var back_bg = require('./../img/menu.png');

Reactjs Methods in React Native to Find DOM Node Dimensions

How can the DOM node be obtained from a Component in React Native (v0.5.0)? Based on the code snippet below, "this.refs.abc" does not have the "getDOMNode( )" method. Also, "findDOMNode()" is NOT available in the React module. (Ultimately, I am trying to find out the dimensions of a Component's DOM element).
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
TouchableHighlight,
View,
} = React;
var styles = StyleSheet.create({
button: {
marginHorizontal: 100,
marginVertical: 300,
height: 50,
padding: 5,
backgroundColor: "yellow",
flex: 1,
alignItems: "center",
justifyContent: "center",
},
})
var Test = React.createClass({
handleClick: function(e) {
debugger;
var element = this.refs.abc.getDOMNode();
var element2 = React.findDOMNode(this.refs.abc);
},
render: function() {
return <Abc ref="abc" update={this.handleClick.bind(this)} />
}
});
var Abc = React.createClass({
render: function() {
return (
<TouchableHighlight
underlayColor="#A4A4A4"
style={styles.button}
onPress={() => this.props.update()}>
<View>
<Text>Testing</Text>
</View>
</TouchableHighlight>
);
}
})
AppRegistry.registerComponent('test', () => Test);
There is no DOM. React Native doesn't run inside a web browser and so there's no exact equivalent. To get the dimensions of a component, you can use the measure method that is mixed in to a component:
this.refs.abc.measure(function(x, y, width, height) {
// Do something with position and dimensions
});

react-native propagate changes in props through ListView and Navigator

I have the following situation. I have a parent component that contains a list of items, any of which can be drilled down into and viewed in a child component. From the child component, you should be able to change a value in the item you are looking at.
In the React web world, this would be easy to solve with the parent storing the list as state, and passing the item and a callback for changes as props to the child.
With React Native, it seems like that possibility is lost, since causing a change from the child component does not trigger a re-render until navigating away.
I've recorded a video of what this looks like. https://gfycat.com/GreenAgitatedChanticleer
Code is below.
index.ios.js
var React = require('react-native');
var {
AppRegistry,
Navigator
} = React;
var List = require('./list');
var listviewtest = React.createClass({
render: function() {
return (
<Navigator
initialRoute={{ component: List }}
renderScene={(route, navigator) => {
return <route.component navigator={navigator} {...route.passProps} />;
}} />
);
}
});
AppRegistry.registerComponent('listviewtest', () => listviewtest);
list.js
var React = require('react-native');
var _ = require('lodash');
var {
View,
Text,
TouchableHighlight,
ListView
} = React;
var Detail = require('./detail');
var List = React.createClass({
getInitialState() {
var LANGUAGES = [
{ id: 1, name: 'JavaScript' },
{ id: 2, name: 'Obj-C' },
{ id: 3, name: 'C#' },
{ id: 4, name: 'Swift' },
{ id: 5, name: 'Haskell' }
];
var ds = new ListView.DataSource({ rowHasChanged: (a, b) => a !== b })
return {
languages: LANGUAGES,
ds: ds.cloneWithRows(LANGUAGES)
};
},
goToLanguage(language) {
this.props.navigator.push({
component: Detail,
passProps: {
language: language,
changeName: this.changeName
}
});
},
changeName(id, newName) {
var clone = _.cloneDeep(this.state.languages);
var index = _.findIndex(clone, l => l.id === id);
clone[index].name = newName;
this.setState({
languages: clone,
ds: this.state.ds.cloneWithRows(clone)
});
},
renderRow(language) {
return (
<TouchableHighlight onPress={this.goToLanguage.bind(this, language)}>
<View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', paddingTop: 5, paddingBottom: 5, backgroundColor: '#fff', marginBottom: 1 }}>
<Text style={{ marginLeft: 5, marginRight: 5 }}>{language.name}</Text>
</View>
</TouchableHighlight>
);
},
render() {
return (
<View style={{ flex: 1, backgroundColor: '#ddd' }}>
<Text style={{ marginTop: 60, marginLeft: 5, marginRight: 5, marginBottom: 10 }}>Select a language</Text>
<ListView
dataSource={this.state.ds}
renderRow={this.renderRow} />
</View>
);
}
});
module.exports = List;
detail.js
var React = require('react-native');
var {
View,
Text,
TouchableHighlight
} = React;
var Detail = React.createClass({
changeName() {
this.props.changeName(this.props.language.id, 'Language #' + Math.round(Math.random() * 1000).toString());
},
goBack() {
this.props.navigator.pop();
},
render() {
return (
<View style={{ flex: 1, backgroundColor: '#ddd', alignItems: 'center', justifyContent: 'center' }}>
<Text>{this.props.language.name}</Text>
<TouchableHighlight onPress={this.changeName}>
<Text>Click to change name</Text>
</TouchableHighlight>
<TouchableHighlight onPress={this.goBack}>
<Text>Click to go back</Text>
</TouchableHighlight>
</View>
);
}
});
module.exports = Detail;
Turns out this behavior is intentional, at least for now. There's a discussion thread here: https://github.com/facebook/react-native/issues/795
For anyone looking for a workaround, I'm using RCTDeviceEventEmitter to pass data across Navigator. Updated code below
list.js
var React = require('react-native');
var _ = require('lodash');
var {
View,
Text,
TouchableHighlight,
ListView
} = React;
var Detail = require('./detail');
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var List = React.createClass({
getInitialState() {
var LANGUAGES = [
{ id: 1, name: 'JavaScript' },
{ id: 2, name: 'Obj-C' },
{ id: 3, name: 'C#' },
{ id: 4, name: 'Swift' },
{ id: 5, name: 'Haskell' }
];
var ds = new ListView.DataSource({ rowHasChanged: (a, b) => a !== b })
return {
languages: LANGUAGES,
ds: ds.cloneWithRows(LANGUAGES)
};
},
goToLanguage(language) {
this.props.navigator.push({
component: Detail,
passProps: {
initialLanguage: language,
changeName: this.changeName
}
});
},
changeName(id, newName) {
var clone = _.cloneDeep(this.state.languages);
var index = _.findIndex(clone, l => l.id === id);
clone[index].name = newName;
RCTDeviceEventEmitter.emit('languageNameChanged', clone[index]);
this.setState({
languages: clone,
ds: this.state.ds.cloneWithRows(clone)
});
},
renderRow(language) {
return (
<TouchableHighlight onPress={this.goToLanguage.bind(this, language)}>
<View style={{ flex: 1, flexDirection: 'row', alignItems: 'center', paddingTop: 5, paddingBottom: 5, backgroundColor: '#fff', marginBottom: 1 }}>
<Text style={{ marginLeft: 5, marginRight: 5 }}>{language.name}</Text>
</View>
</TouchableHighlight>
);
},
render() {
return (
<View style={{ flex: 1, backgroundColor: '#ddd' }}>
<Text style={{ marginTop: 60, marginLeft: 5, marginRight: 5, marginBottom: 10 }}>Select a language</Text>
<ListView
dataSource={this.state.ds}
renderRow={this.renderRow} />
</View>
);
}
});
module.exports = List;
detail.js
var React = require('react-native');
var {
View,
Text,
TouchableHighlight
} = React;
var RCTDeviceEventEmitter = require('RCTDeviceEventEmitter');
var Detail = React.createClass({
getInitialState() {
return {
language: this.props.initialLanguage,
subscribers: []
};
},
componentDidMount() {
var subscriber = RCTDeviceEventEmitter.addListener('languageNameChanged', language => {
this.setState({ language });
});
this.setState({
subscribers: this.state.subscribers.concat([subscriber])
});
},
componentWillUnmount() {
this.state.subscribers.forEach(sub => {
console.log('removing');
sub.remove();
});
},
changeName() {
this.props.changeName(this.state.language.id, 'Language #' + Math.round(Math.random() * 1000).toString());
},
goBack() {
this.props.navigator.pop();
},
render() {
return (
<View style={{ flex: 1, backgroundColor: '#ddd', alignItems: 'center', justifyContent: 'center' }}>
<Text>{this.state.language.name}</Text>
<TouchableHighlight onPress={this.changeName}>
<Text>Click to change name</Text>
</TouchableHighlight>
<TouchableHighlight onPress={this.goBack}>
<Text>Click to go back</Text>
</TouchableHighlight>
</View>
);
}
});
module.exports = Detail;
I wanted to propagate prop change to the rest of route stack as well. And I don't find any way to render renderScene() from the first route.. So I use navigator.replace() instead of updating props. I'm looking for the better way to deal with this because I believe there are a lot of use-case to deal with the route[0] that has info and need to propagate the change to the rest of route stack, like what we do on React props between parent and its children.
# this is on parent component and the change is pushed to props(I'm using Redux)
componentWillReceiveProps(nextProps){
this.props.hubs.map((currentHub) => {
nextProps.hubs.map((hub) => {
if(currentHub.updatedAt !== hub.updatedAt){
this.props.navigator.getCurrentRoutes().map((r, index) => {
if(r.getHubId && ( r.getHubId() === hub.objectId ) ){
let route = Router.getHubRoute(hub);
this.props.navigator.replaceAtIndex(route, index);
}
});
}
})
})

Resources