How to create an object in react native? - react-native

I just started learning react native and I am having issues with creating an object. Here is the code
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
} from 'react-native';
export default class object {
name: 'joe'
age: 27
country: 'France'
}
And when I try to instantiate it in another class like this
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
} from 'react-native';
import object from './object.js'
export default class MyComponent extends Component {
var man = new Object();
render() {
return (
<View style={styles.container}>
<Text>{man.age}</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
})
I get a syntax error Unexpected token var ->man = new Object(). How do I fix this?

Try to create your object in typescript file(object.ts) for exemple:
export class object {
name: 'joe',
age: 27,
country: 'France'
constructor(obj) {
this.name=obj.key;
this.age=obj.nom;
this.country=obj.prenom;
}
}

the wrong part is you export default class object, FYI: CLASS is not OBJECT
the correct using of export is
export const object = {
name: 'joe',
age: 27,
country: 'France'
}
then you can import it with
import {object} from './object.js'

Related

null is not an object (evaluating 'this.nativeCommandsModule.push')

I am using WIX-React-Native-Navigation and while pushing a component in the stack I am getting this error.
Error
One thing to say, I am using Viro-React ARScene Navigation (Scene Navigation) in WIX-React-Native-Navigation.
Here's my code
index.js
import { AppRegistry } from 'react-native';
var OpenDoor = require('./app/base')
import Stack from './app/navigation';
import { Navigation } from "react-native-navigation";
AppRegistry.registerComponent('ViroSample', () => OpenDoor);
Navigation.events().registerAppLaunchedListener(() => {
Navigation.setRoot({
root: {
stack: Stack
}
});
});
navigation.js
import { Navigation } from "react-native-navigation";
import Base from './base';
import Menu from './components/Menu/menu';
Navigation.registerComponent('Base', () => Base);
Navigation.registerComponent('Menu', () => Menu);
const Stack = {
children: [{
component: {
name: 'Base'
},
}
]
};
export default Stack;
base.js
import React, {Component} from 'react';
import {
Alert,
View
} from 'react-native';
import {ViroARSceneNavigator} from 'react-viro';
import { Navigation } from 'react-native-navigation';
import APIKeys from './index';
import Camera from './components/Camera/camera';
import MenuButton from './components/Menu/menu_button';
class Base extends Component {
constructor(props) {
super(props);
this.navigateScreen = this.navigateScreen.bind(this);
}
navigateScreen(location) {
Navigation.push(this.props.componentId, {
component: {
name: location
}
});
}
render() {
return(
<View style={styles.container}>
<ViroARSceneNavigator
initialScene = {{
scene: Camera
}}
apiKey = {APIKeys.ViroReact}
style = {styles.ar_scene}
/>
<MenuButton navigation={this.navigateScreen}/>
</View>
);
}
};
const styles = {
container: {
flex: 1
}
};
export default Base;
module.exports = Base;
Correct me, If I am wrong somewhere.
What I am doing is, creating an application where users can decorate home virtually with the help of Augmented Reality. The mobile app is created on React-Native while the library used for augmented reality is Viro-React.
So, When I want to navigate from One Screen to another, then while pushing component in the stack I am getting this error.
Thanks.

React StackNavigator with lifted state howto

I work with StackNavigator for navigation between a couple of screens. In these screens i will collect user information. I would like this information to be stored in one state so each view will have the same information.
I got this working but i think it is not the correct or ideal because i keep track of 2 states. One in the starting view and one in the current view.
Hence my question is, is it possible to work with only one state?
Here is my code:
My root class which creates the StackNavigator:
//#flow
import React from 'react';
import {StackNavigator} from 'react-navigation';
import Cart from './Cart';
import DeliveryAddress from './DeliveryAddress';
import Queue from './Queue';
export type State = {
text: string,
user: string,
onChange: Function
}
const Screens = StackNavigator({
Cart: {
screen: Cart
},
Queue: {
screen: Queue
},
DeliveryAddress: {
screen: DeliveryAddress
}
});
const AppNavigation = () => (<Screens/>);
export default class Root extends React.Component < Object,
State > {
render() {
return <AppNavigation/>;
}
}
Here my first view the Cart:
// #flow
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Text, View, Button} from 'react-native';
import DeliveryAddress from './DeliveryAddress';
import type {State}
from './Root';
export default class Cart extends Component < Object,
State > {
static navigationOptions = {
title: 'Welcome'
};
handleChange: Function;
getState: Function;
constructor(props : Object) {
super(props);
console.log("Construction Cart with state");
console.log(this);
console.log("props");
console.log(this.props);
this.handleChange = this.handleChange.bind(this);
this.state = {
user: "Lucy",
text: "Vul in",
onChange: this.handleChange,
getState: this.getState
};
}
handleChange(data : Object) {
this.setState(...data);
}
render() {
const {navigate} = this.props.navigation;
return (<View>
<Text>This is your cart.</Text>
<Button onPress={() => navigate('DeliveryAddress', this.state)} title="Go to delivery address"/>
</View>);
}
}
and here is my second view:
// #flow
import React, {Component} from 'react';
import {Text, View, Button, TextInput} from 'react-native';
import type {NavigationScreenProp}
from 'react-navigation/src/TypeDefinition';
import type {State}
from './Root';
type NavigationType = {
navigation: NavigationScreenProp < NavigationState >
}
type NavigationState = {
params: {
user: "bar"
}
}
export default class DeliveryAddress extends Component < any,
State > {
// Nav options can be defined as a function of the screen's props:
static navigationOptions = ({navigation} : NavigationType) => ({title: `Delivery address of ${navigation.state.params.user}`});
handleChange: Function;
constructor(props : Object) {
super(props);
this.state = props.navigation.state.params;
console.log(props.navigation.state);
this.handleChange = this.handleChange.bind(this);
}
handleChange(data : Object) {
this.setState(data);
this.state.onChange(data);
}
render() {
console.log("welkom in delivery address");
// The screen's current route is passed in to `props.navigation.state`:
const {navigate} = this.props.navigation;
return (<View>
<Text>User name: {this.state.user}</Text>
<TextInput style={{
height: 40,
borderColor: 'gray',
borderWidth: 1
}} onChangeText={(text) => this.handleChange({text})} value={this.state.text}/>
<Button onPress={() => navigate('Queue', this.state)} title={this.state.text}/>
</View>);
}
}
The thing is that i need to set both states like this:
handleChange(data : Object) {
this.setState(data);
this.state.onChange(data);
}
Is this the best way of doing this?
it seems that there is a nice way to solve this: Using Redux with a Provider.
with the provider it is possible do add information to a 'context':
import {Provider, connect} from "react-redux";
return (<Provider store={store}>
<AppNavigation/>
</Provider>);
the provider will add the store to the context. Any child (and grandchild) can use this store like this:
console.log("this.context");
console.log(this.context);
const {store} = this.context;
above will only work if you add this into the component:
Cart.contextTypes = {
store: PropTypes.object
}
here is more info:
https://egghead.io/lessons/react-redux-passing-the-store-down-implicitly-via-context

how can use a function in props of react native?

I need to pass a function on the props. I have this component:
import React, {Component} from 'react';
import { View } from 'react-native';
import {FBLogin, FBLoginManager} from 'react-native-facebook-login';
const Loginfb = (props) => (
<FBLogin
style={{marginBottom: 10}}
ref={props.ref}
permissions={["email", "user_friends"]}
loginBehavior={FBLoginManager.LoginBehaviors.SystemAccount}
onLogin={props.login}
);
export default Loginfb;
Where props.ref and props.login are functions with data. In my container component I have this:
import React, {Component} from 'react';
import {View} from 'react-native';
import {FBLogin, FBLoginManager} from 'react-native-facebook-login';
import Loginfb from '../components/fblogin';
class Inicio extends Component {
constructor(props) {
super(props);
this.state = {
user: null,
};
}
Ref = (fbLogin) => {
this.fbLogin = fbLogin
}
login = (data) => {
console.log("Logged in!");
console.log(data);
this.setState({user: data.credentials});
}
render() {
return (
<View
<Loginfb
ref={this.ref}
onLogin={this.login}/>
</View>
);
}
}
export default Inicio;
I can't understand my error: "this.props[event] is not a function"
Please Help.
Not quite sure, but I'm assuming the context is lost.
Either inline when you pass them to the child:
myFunction.bind(this)
Or in the constructor of the container, like so:
this.myFunction = this.myFunction.bind(this)
Hope this helps.

Set and access mutable app global params with React Navigation in React Native

Is there a way I can declare mutable global parameters within React Navigation StackNavigator? I'm trying to achieve a central point of reference for global variables in the app.
Suppose this is my index.android.js :
import {
AppRegistry
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import {MainScreen} from './components/mainScreen';
import {SegundoScreen} from './components/segundoScreen';
import {TerceraScreen} from './components/terceraScreen';
const SampleAppStack = StackNavigator(
{
Home : { screen : MainScreen },
SegundoScreen : { screen : SegundoScreen },
TerceraScreen : { screen : TerceraScreen }
},
{
headerMode: 'none'
},
{
appGlobalVariables: {
Session : '',
variable1 : 'cool',
variable2 : 'coolant',
variable3 : 'color',
variable4 : 'none',
objetoUno : {},
objetoDos : {},
objetoTres : {}
}
}
);
AppRegistry.registerComponent('SampleApplication', () => SampleAppStack);
Then in directory components/mainScreen.js, I supposedly have...
import React, { Component } from 'react';
import {Text,View} from 'react-native';
import { StackNavigator } from 'react-navigation';
class MainScreen extends Component {
constructor(props) {
super(props);
this.state = {dummyProp:'dummyProp'};
}
render() {
var {appGlobalVariables} = this.props.StackNavigator;
return (
<View>
<Text>Received from App's global variables: {appGlobalVariables.variable1}</Text>
</View>
);
}
}
export {MainScreen}
And in directory components/segundoScreen.js, I supposedly have...
import React, { Component } from 'react';
import {Text,View} from 'react-native';
import { StackNavigator } from 'react-navigation';
class SegundoScreen extends Component {
constructor(props) {
super(props);
this.state = {dummyProp:'dummyProp'};
}
render() {
var {appGlobalVariables} = this.props.StackNavigator;
return (
<View>
<Text>Received from App's global variables: {appGlobalVariables.variable2}</Text>
</View>
);
}
}
export {SegundoScreen}
And in directory components/terceraScreen.js, I supposedly have...
import React, { Component } from 'react';
import {Text,View} from 'react-native';
import { StackNavigator } from 'react-navigation';
class TerceraScreen extends Component {
constructor(props) {
super(props);
this.state = {dummyProp:'dummyProp'};
}
render() {
var {appGlobalVariables} = this.props.StackNavigator;
return (
<View>
<Text>Received from App's global variables: {appGlobalVariables.variable3}</Text>
</View>
);
}
}
export {TerceraScreen}
I've tried it, but it is not working.
An option would be to use global like mentioned here https://stackoverflow.com/a/36994650/4805414. Also see accepted answer to the belonging question. Maybe that's an alternative for you, too.

MobX with React Native: store is undefined

This is my first go at using MobX so this may be a simpler problem than I imagine, but I'm not getting any errors with the things I've tried; the store is simply undefined wherever I try to use it. I've tried both importing the store directly into components and passing props from the main file (also with , but I'm not sure if I used that right). I've experimented with several different .babelrc file settings as well, but that doesn't seem to be an issue.
Here is the UserStore:
import React from 'react';
import { observable } from 'mobx';
class UserStore {
#observable info = {
username: "bob",
password: "secret",
email: "bob#email.com"
}
}
const userStore = new UserStore()
export default userStore;
Here is a simplified App.js:
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Profile from './app/Profile.js';
import { UserStore } from './app/UserStore.js';
export default class App extends Component {
constructor(){
super();
this.state = {
page: 'Profile',
}
}
changePage(){
switch (this.state.page) {
case "Profile":
return <Profile logout={this.logout.bind(this)} userStore={UserStore}/>;
}
}
render() {
return (
<View>
{this.changePage()}
</View>
);
}
}
And here is a simplified Profile.js:
import React, { Component } from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { observer } from 'mobx-react/native';
#observer
export default class Profile extends Component {
render() {
console.log(this.props.userStore);
return (
<View>
<Text>Profile Page</Text>
<Text>username: {props from store go here}</Text>
<Text>password: {props from store go here}</Text>
<Text>email: {props from store go here}</Text>
</View>
);
}
}
All I'm trying to do right now is get the pre-defined observable "info" object from the store to the Profile.js component and display that information. This is being way more difficult than it should be - any insight is greatly appreciated!
Since you declared export default userStore; in UserStore.js
Try changing the way you import in App.js by removing the {}:
import UserStore from './app/UserStore.js';
{} is needed only if you want to do a named import. Here is a good read if you want to know more.