Usage of navigator in react-native - javascript

I am new to react-native framework and learning how to use navigator. I tried to implement jump between two pages of APP. From "Boy" to "Girl" then back to "Boy".
Here is the code in APP.js:
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, {Component, } from 'react';
import {
Platform,
StyleSheet,
Text,
View,
Image,
} from 'react-native';
import Boy from './Boy';
import {Navigator} from 'react-native-deprecated-custom-components';
import TabNavigator from 'react-native-tab-navigator';
export default class imooc_gp extends Component {
constructor(props){
super(props);
this.state = {
selectedTab:'tb_popular',
}
}
render() {
return (
<View style={styles.container}>
<Navigator
initialRoute = {{
title:'example',
component: Boy
}}
renderScene = {(route, navigator) =>{
let Component = route.component;
return <Component navigator = {navigator} {...route.params}/>
}}
></Navigator>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#F5FCFF',
},
page1 :{
flex: 1,
backgroundColor: 'red',
},
page2: {
flex: 1,
backgroundColor: 'yellow',
},
image: {
height: 22,
width: 22,
}
});
Boy.js:
import React, {Component} from 'react';
import {
View,
Text,
StyleSheet
}from 'react-native';
import Girl from './Girl';
export default class Boy extends Component{
constructor(props){
super(props);
this.state = {
word: ''
}
}
render(){
return (
<View style = {styles.container}>
<Text style = {styles.text}> I am a boy</Text>
<Text style = {styles.text}
onPress = {()=>{
this.props.navigator.push({
title:'Girl',
component: Girl,
params:{
word: 'A Rose',
onCallBack: (word)=>{
this.setState({
word: word
})
}
}
})
}}>Send girl a Rose</Text>
<Text style = {styles.text}>{this.state.word}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'gray',
justifyContent: 'center'
},
text: {
fontSize: 20,
}
})
Girl.js:
import React, {Component} from 'react';
import {
View,
Text,
StyleSheet
}from 'react-native';
export default class Girl extends Component{
constructor(props){
super(props);
this.state = {
}
}
render(){
return(
<View styles = {styles.container}>
<Text style = {styles.text}> I am a Girl</Text>
<Text style = {styles.text}>{this.state.word}</Text>
<Text style = {styles.text}
onPress = {()=>{
this.props.onCallBack('A box of chocolate')
this.props.navigator.pop()
}}>return chocolate</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'red',
justifyContent: 'center',
},
text: {
fontSize: 22
}
})
And I received the error message on iPhone emulator showed in the image:
I guess the error could be caused by wrong usage grammar of Navigator in different react-native version.

In my experience, I have found it more useful to use react-navigation library. This allows one to create a router files that lists all the pages that you want your app to navigate around; in your case, it could be Boy.js and Girl.js. Example given below:
import React from 'react';
import { StackNavigator } from 'react-navigation';
import { Boy, Girl } from '../app';
export const Screens = StackNavigator({
Boy: {
screen: Boy,
},
Girl: {
screen: Girl
}
});
And once you render the Screen component, Boy.js and Girl.js will each have access to the other screen via the "navigation.navigate" props.
So in your Boy component, rather than:
onPress = {()=>{
this.props.navigator.push({
title:'Girl',
component: Girl,
params:{
word: 'A Rose',
onCallBack: (word)=>{
this.setState({
word: word
})
}
}
})
You could simply write:
this.props.navigation.navigate("Girl")
All you would need to do is import the Girl component.
Hope this helps!

Related

React360-Redux:Communication between 2 roots components via redux

I have 2 root components in react360.I have the main panel with information and my products and i have my 3d model.I want to communicate one another.Μore specifically I just want to click on the product then the color from my 3d model changes.At this time, my 3d model has value from the store I have originally defined, but while the price is changing, it is not renewed in the 3d model.for example when the application starts the original color of my model is blue but when I click on the first item it does not change to red. Wrere is the problem?????before
after
client.js
import { ReactInstance } from "react-360-web";
import { Location } from "react-360-web";
function init(bundle, parent, options = {}) {
const r360 = new ReactInstance(bundle, parent, {
// Add custom options here
fullScreen: true,
...options
});
// Render your app content to the default cylinder surface
r360.renderToSurface(
r360.createRoot("Center", {
/* initial props */
}),
r360.getDefaultSurface()
);
r360.renderToLocation(
r360.createRoot("React3DView"),
r360.getDefaultLocation()
);
// Load the initial environment
r360.compositor.setBackground(r360.getAssetURL("360_world.jpg"));
}
window.React360 = { init };
index.js
import { AppRegistry } from "react-360";
import Center from "./components/center";
import React3DView from "./components/obj";
AppRegistry.registerComponent("Center", () => Center);
AppRegistry.registerComponent("React3DView", () => React3DView);
reducer
initialState = {
data: [
{ id: 1, value: "MILEPTY.png" },
{ id: 2, value: "cleveland.png" },
{ id: 3, value: "phila.png" },
{ id: 4, value: "raptors.png" },
{ id: 5, value: "rockets.png" }
],
currentinfo: "Hello.Press click on T-shirt to show information",
currentcolor: "blue"
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case "INFO":
if (action.key === 1) {
return {
...state,
currentinfo: "Milwaukee bucks",
currentcolor: "red"
};
}
if (action.key === 2) {
return {
...state,
currentinfo: "Cleveland Cavaliers",
currentcolor: "green"
};
}
if (action.key === 3) {
return { ...state, currentinfo: "Philadelphia 76xers" };
}
if (action.key === 4) {
return { ...state, currentinfo: "Toronto Raptors" };
}
if (action.key === 5) {
return { ...state, currentinfo: "Huston Rockets" };
}
default:
return state;
}
};
export default reducer;
centerPanel
import React from "react";
import { AppRegistry, StyleSheet, Text, View, Image, asset } from "react-360";
import Products from "./products";
import { connect } from "react-redux";
class CenterPanel extends React.Component {
render() {
return (
<View style={styles.panel}>
<View style={{ flex: 1, flexDirection: "row" }}>
<View
style={{
width: 250,
height: 600
}}
>
<Text style={{ marginTop: "100" }}>{this.props.currentinfo}</Text>
</View>
<View
style={{
width: 1000,
height: 600,
backgroundColor: "green"
}}
>
<View style={{ flex: 1, flexDirection: "row" }}>
{this.props.data.map(element => (
<Products
key={element.id}
value={element.value}
id={element.id}
/>
))}
</View>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
panel: {
// Fill the entire surface
width: 1000,
height: 600,
backgroundColor: "rgba(255, 255, 255, 0.4)"
}
});
const mapStateToProps = state => {
return {
data: state.data,
currentinfo: state.currentinfo
};
};
export default connect(mapStateToProps)(CenterPanel);
products
import React from "react";
import { AppRegistry, StyleSheet, Text, View, Image, asset } from "react-360";
import { connect } from "react-redux";
class Products extends React.Component {
state = {
img: this.props.value
};
render() {
return (
<View
style={styles.panelimages}
onInput={() => this.props.onText(this.props.id)}
>
<Image style={styles.images} source={asset(this.state.img)} />
</View>
);
}
}
const styles = StyleSheet.create({
panelimages: {
width: 150,
height: 150,
marginTop: 200,
backgroundColor: "white"
},
images: {
width: 150,
height: 150
}
});
const mapDispatchToProps = dispatch => {
return {
onText: id => dispatch({ type: "INFO", key: id })
};
};
export default connect(
null,
mapDispatchToProps
)(Products);
center
import React from "react";
import { AppRegistry, StyleSheet, Text, View, Image, asset } from "react-360";
import { createStore } from "redux";
import { Provider } from "react-redux";
import reducer from "../store/reducer";
import CenterPanel from "./centerPanel";
// const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
const store = createStore(reducer);
export default class Center extends React.Component {
render() {
return (
<Provider store={store}>
<CenterPanel />
</Provider>
);
}
}
objpanel
import React from "react";
import {
asset,
AppRegistry,
StyleSheet,
Text,
View,
VrButton,
Image
} from "react-360";
import Entity from "Entity";
import { connect } from "react-redux";
class Object3d extends React.Component {
render() {
return (
<View>
<Entity
source={{ obj: asset("t-shirt.obj") }}
style={{
transform: [{ translate: [-3.5, -3.5, -2.8] }],
color: this.props.currentcolor -------->here is problem
}}
/>
</View>
);
}
}
const mapStateToProps = state => {
return {
currentcolor: state.currentcolor
};
};
export default connect(mapStateToProps)(Object3d);
obj
import React from "react";
import { AppRegistry, StyleSheet, Text, View, Image, asset } from "react-360";
import { createStore } from "redux";
import { Provider } from "react-redux";
import reducer from "../store/reducer";
import Object3d from "./objpanel";
// const store = createStore(reducers, {}, applyMiddleware(ReduxThunk));
const store = createStore(reducer);
export default class React3DView extends React.Component {
render() {
return (
<Provider store={store}>
<Object3d />
</Provider>
);
}
}
I've tried to do this with redux but in the end I had more problems implementing it than it was worth. In order to implement something like that you would need to follow the code that is described here:
React 360 multi panel example
Additionally, I've implemented what you are trying to do without redux. You can look at the code in this repository and also view the production link here. Its modeled after the react 360 code.
CryptoDashboardVR repo
CryptodashboardVR Multipanel synchronization
Finally, If you still need help, check out my course on React 360. I explain the concepts used. Udemy react 360.
Hope that helps. For now, I would abandon the redux approach until maybe 2.0 comes out.

Custom input component in react native input is not working as expected

I am trying to make a custom input component with onChangeText but whenever I start typing in the textInput box I get an error. I have checked the code many times and everything looks fine to me.
import React from "react";
import { TextInput, StyleSheet } from "react-native";
const defaultInput = props => (
<TextInput
underlineColorAndroid="transparent"
{...props}
style={[styles.input, props.style]}
/>
)
const styles = StyleSheet.create({
input: {
width: "100%",
borderWidth: 1,
borderColor: "#eee",
padding: 5,
marginTop: 8,
marginBottom: 8
}
});
export default defaultInput;
This is my sub component where I am using my custom component.
import React, { Component } from "react";
import { View, TextInput, Button, StyleSheet } from "react-native";
import DefaultInput from "../UI/DefaultInput/DefaultInput";
const placeInput = props =>(
<DefaultInput
placeholder="Place Name"
value={props.placeName}
onChangeText={props.onChangeText}
/>
)
export default placeInput;
This is the screen where I am using my sub component.
import React, { Component } from 'react'
import { Text, View, TextInput, Button, StyleSheet, ScrollView, Image } from 'react-native'
import { connect } from 'react-redux'
import placeImage from '../../asset/pic.jpg'
import PlaceInput from '../../component/PlaceInput/PlaceInput'
import { addPlace } from '../../store/actions/index'
import { Navigation } from 'react-native-navigation'
// import DefaultInput from '../../component/UI/DefaultInput/DefaultInput'
import HeadingText from '../../component/UI/HeadingText/HeadingText'
import MainText from '../../component/UI/MainText/MainText'
import PickImage from '../../component/PickImage/PickImage'
import PickLocation from '../../component/PickLocation/PickLocation'
class SharePlace extends Component {
state={
placeName:""
}
constructor(props) {
super(props);
this.props.navigator.setOnNavigatorEvent(this.OnNavigatorEvent);
}
placeNameChangedHandler = val => {
this.setState({
placeName: val
});
};
OnNavigatorEvent = (event) => {
console.log(event);
if (event.type === "NavBarButtonPress") {
if (event.id === "sideDrawerToggle") {
this.props.navigator.toggleDrawer({
side: "left"
})
}
}
}
placeAddedHandler = () => {
if(this.state.placeName.trim() !== "")
{
this.props.onAddPlace(this.state.placeName);
}
}
render() {
return (
// <ScrollView contentContainerStyle={styles.conatiner}>
<ScrollView>
<View style={styles.conatiner}>
<MainText>
<HeadingText>Share a place with us!</HeadingText>
</MainText>
<PickImage />
<PickLocation />
<PlaceInput
placeName={this.state.placeName}
onChangeText={this.placeNameChangedHandler}
/>
<View style={styles.button}>
<Button title="share the place" onPress={this.placeAddedHandler} />
</View>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
conatiner: {
flex: 1,
alignItems: "center"
},
placeholder: {
borderWidth: 1,
borderColor: "black",
backgroundColor: "#eee",
width: "80%",
height: 150
},
button: {
margin: 8
},
imagePreview: {
width: "100%",
height: "100%"
}
})
const mapDispatchToProps = dispatch => {
return {
onAddPlace: (placeName) => dispatch(addPlace(placeName))
}
}
export default connect(null, mapDispatchToProps)(SharePlace)
This is the error I am getting.
ExceptionsManager.js:63 Invariant Violation: TextInput(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
This error is located at:
in TextInput (at DefaultInput.js:5)
in defaultInput (at PlaceInput.js:7)
in placeInput (at SharePlace.js:60)
in RCTView (at View.js:60)
in View (at SharePlace.js:54)
in RCTScrollContentView (at ScrollView.js:791)
in RCTScrollView (at ScrollView.js:887)
in ScrollView (at SharePlace.js:53)
in SharePlace (created by Connect(SharePlace))
in Connect(SharePlace) (at Navigation.js:83)
in Provider (at Navigation.js:82)
in _class2 (at renderApplication.js:33)
in RCTView (at View.js:60)
in View (at AppContainer.js:102)
in RCTView (at View.js:60)
in View (at AppContainer.js:122)
in AppContainer (at renderApplication.js:32)
Using typescript,
import {TextInput, TextInputProps, View} from "react-native";
declare a props interface:
interface Props extends TextInputProps {}
// This ensures that all the properties associated with react-native's
// TextInput component, are associated with your custom-input component as well.
decalare your custom-input component:
const CustomInput = (props: Props) => {
<TextInput onChangeText={props.onChangeText} placeholder={props.placeholder} style={[props.style]} />
}
export default CustomInput;
use your custom-input component in LoginScreen.tsx say;
import React from "react";
import CustomInput from "../CustomInput";
const LoginScreen = () => {
const handleChange = (value: string) =>{
....
}
return(
<CustomInput placeholder="email" onChangeText={value => handleChange(value) />
)
your code working fine as the way I ran it, maybe you have problem to import PlaceInput or DefaultInput:
import React, { Component } from 'react';
import { View, Text, FlatList, ScrollView,TextInput, Image,StyleSheet } from 'react-native';
export default class Test extends Component {
constructor(props) {
super(props);
this.state = {
placeName: ""
}
}
placeNameChangedHandler = val => {
this.setState({
placeName: val
});
};
render() {
return (
<View>
<PlaceInput
placeName={this.state.placeName}
onChangeText={this.placeNameChangedHandler}
/>
</View>
);
}
}
const PlaceInput = props => (
<DefaultInput
placeholder="Place Name"
value={props.placeName}
onChangeText={props.onChangeText}
/>
)
const DefaultInput = props => (
<TextInput
underlineColorAndroid="transparent"
{...props}
style={[styles.input, props.style]}
/>
)
const styles = StyleSheet.create({
input: {
width: "100%",
borderWidth: 1,
borderColor: "#eee",
padding: 5,
marginTop: 8,
marginBottom: 8
}
});

undefined is not an object (evaluating '_this.props.navigator.push')

I'm trying to navigate from Homescreen to another screen(Test).I have 'HomeScreen.js' below. Once I click on the register button, I get the above mentioned error.
I've been at this for a whole day, but can't seem to get a straight forward answer.
The error is on my 'Homescreen.js' (Attached screenshot error)
Screenshot
Error is pointing to: this.props.navigator.push under the _handleRegisterView function.
HomeScreen.js
import React from 'react';
import {
StyleSheet,
Text,
View,
AsyncStorage,
Component,
TouchableHighlight,
AppRegistry
} from 'react-native';
import Test from './Test';
import { StackNavigator } from 'react-navigation';
class HomeScreen extends React.Component {
static navigationOptions = {
title: 'SpeedHack',
};
_handleRegisterView = () => {
this.props.navigator.push({
title: 'Test',
component: Test,
backButtonTitle: 'Back'
})
//alert('Register button Pressed!.');
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={this._handleRegisterView}>
<Text style={[styles.button, styles.blueButton]}>
Register
</Text></View>
);
}
}
Test.js (Doesn't really do anything interesting, loads an image)
import React from 'react';
import { Component, StyleSheet, Text, View, Image } from 'react-native';
class Test extends React.Component {
render() {
let pic = {
uri: 'https://upload.wikimedia.org/wikipedia/commons/d/de/Bananavarieties.jpg'
};
return (
<View style={styles.container}>
<Text>Ssup Dude! Want some bananas?</Text>
<Image source = {pic} style = {{width: 300, height: 300}}/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
You seem to be confused. In react-navigation in order to push a screen, you do not do this.props.navigator.push, you use this.props.navigation.navigate.

React Native Invariant Violation: View config

I'm trying to practice with different screens on a React Native project. Here's my code from App.js file.
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import { StackNavigator } from 'react-navigation';
class HomeScreen extends React.Component {
static navigationOptions = {
title: "welcome",
};
render() {
return <Text style={{ color: 'black '}}>Hello, Navigation!</Text>;
}
}
const navigation = StackNavigator({
Home: { screen: HomeScreen },
});
export default class App extends Component<{}> {
render() {
return <navigation/>;
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
},
});
When I run react-native run-android I get an Invariant Violation which tells me "to view config not found or name navigation". And then all the sites where this violation happens.
Help please thanks.
The name of any component must be capitalized. In your name, the component "navigation" is not capitalized. It should be "Navigation".
In react native the component's name should begin with capital letter, so it will be:
const Navigation = StackNavigator({
Home: { screen: HomeScreen },
});
and call it with capital:
export default class App extends Component<{}> {
render() {
return <Navigation/>;
}
}

How to access state when passing parameters using Stack Navigator in React Native

I've been working on my first React Native project. It is a Multiscreen App, and one of the screens requires some data, which I'm passing from the parent screen. But the issue is that when I receive the data in the child screen, and try to save the value in the screen's state, the app crashes. As soon as I remove the code that accesses the state, it does not crash. Here's the code:
renderRow(object) { //Calling the second screen when the user touches
const { navigate } = this.props.navigation;
return(
<TouchableOpacity onPress={() => navigate('ViewRecord', { key: object.key })}> //Sending the parameter
<Image
styleName="large-square"
source={{ uri: object.record.image }} >
<Text style={styles.designNumberHeading}>{object.record.designNumber}</Text>
</Image>
</TouchableOpacity>
);
}
Here is the code of the Child Screen:
'use-strict'
import React, { Component } from 'react';
import {
StyleSheet,
View,
KeyboardAvoidingView,
ScrollView,
TouchableHighlight,
Text,
FlatList,
} from 'react-native';
import {
Heading,
Title,
TextInput,
Button,
Image,
NavigationBar,
ListView,
TouchableOpacity,
Icon,
Lightbox,
Overlay,
} from '#shoutem/ui';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import NavBar from '../components/NavBar.js';
import { firebaseApp } from '../config/firebase.js';
export default class ViewRecord extends Component{
constructor(props) {
super(props);
this.state={
designNumber: '',
dates: [],
quantity: 0,
karigars: [],
colour:'',
amount: '',
description: '',
editMode: false,
};
this.updateStateAfterGettingData = this.updateStateAfterGettingData.bind(this);
}
getData() {
const { params } = this.props.navigation.state; //Accessing the parameters
console.log('Key: ', params.key);
let databaseRef = firebaseApp.database().ref(params.key);
databaseRef.once('value', (snap) => {
console.log('Inside Event Listener');
this.updateStateAfterGettingData(snap); //Setting the state. (The App crashes if this statement is executed)
});
}
updateStateAfterGettingData(snap) {
this.setState({
designNumber: snap.val().designNumber,
dates: snap.val().dates,
quantity: snap.val().quantity,
karigars: snap.val().karigars,
colour: snap.val().colour,
amount: snap.val().amount,
materials: snap.val().materials,
description: snap.val().description,
});
console.log(this.state);
}
render() {
const { goBack } = this.props.navigation;
this.getData();
if (!this.state.editMode) {
return(
<View style={styles.container}>
<NavBar title="View Record" hasHistory={true} goBack={() => goBack()}/>
</View>
);
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#FFFFFF',
},
})
Here is the code of the StackNavigator:
import { StackNavigator } from 'react-navigation';
import CreateRecord from '../screens/CreateRecord.js';
import Records from '../screens/Records.js';
import ViewRecord from '../screens/ViewRecord.js';
export const Navigator = StackNavigator({
Records: { screen: Records },
CreateRecord: { screen: CreateRecord },
ViewRecord: { screen: ViewRecord },
},
{
headerMode: 'none',
navigationOptions: {
headerVisible: false,
}
});
Now, how can I manipulate the state of the ViewRecord.js class when accepting parameters?
PS: I am using Expo along with Create React Native App

Categories

Resources