It gives this error while running: undefined is not a function (evaluating '_reactNativr.default.createElement') - react-native

This section of code is not running it always return en error saying undefined or not a function in the render function().
Heading
'use strict';
import React, {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
AlertIOS,
Dimensions,
BackHandler,
PropTypes,
Component,
} from 'react-native';
import NavigationExperimental from 'react-native-deprecated-custom-
components';
var _navigator;
//var Navipanel=require('./App/Navigation/Navipanel.js');
var Dashboard= require('./App/Dashboard/dashboard.js');
//var Sample= require('./App/Navigation/sample.js');
var Matches = require('./App/Components/Matches.js');
var Users = require('./App/Components/Users.js');
var SCREEN_WIDTH =require('Dimensions').get('window').width;
var BaseConfig=NavigationExperimental.Navigator.SceneConfigs.FloatFromRight;
var CustomLeftToRightGesture = Object.assign({}, BaseConfig.gestures.pop,
{
snapVelocity: 8,
edgeHitWidth: SCREEN_WIDTH,
});
BackHandler.addEventListener('hardwareBackPress', () => {
if (_navigator.getCurrentRoutes().length === 1) {
return false;
}
_navigator.pop();
return true;
});
var CustomSceneConfig = Object.assign({}, BaseConfig, {
// A very tighly wound spring will make this transition fast
springTension: 100,
springFriction: 1,
// Use our custom gesture defined above
gestures: {
pop: CustomLeftToRightGesture,
}
});
//var createReactElement = require('create-react-element');
var createReactClass = require('create-react-class');
var test = createReactClass({
_renderScene(route,navigator) {
_navigator = navigator;
if (route.id === 1) {
return <Dashboard navigator={navigator}/>;
}
else if(route.id === 2) {
return <Sample navigator={navigator} /> ;
}
else if(route.id === 3) {
return <Navipanel navigator={navigator} /> ;
}
else if(route.id === 4){
return <Matches navigator={navigator} /> ;
}
else if(route.id === 5) {
return <Users navigator={navigator} />
}
},
_configureScene(route) {
return CustomSceneConfig;
},
render:function() {
return (
<NavigationExperimental.Navigator [//error in this line]
initialRoute = {{id:1}}
renderScene = {this._renderScene}
configureScene = {this._configureScene} />
);
}
});
Undefined error _reactNative.default.createElement

You imported React from "react-native";
import React, {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
AlertIOS,
Dimensions,
BackHandler,
PropTypes,
Component,
} from 'react-native';
instead of this, you need to import React from "react";
import React from 'react';
When we use JSX in our render functions, in the background JSX runs React.createElement(...). And in your code, React is not defined. Because of this, it gives that error.

Related

how to set isConnected value false by default in react native

I am new to react native. I have created a nointernet connection check screen. and now I want to test for No internet connection. so How could I set isConnected Value False.
here is my code
import React, { Component } from "react";
import { View, Text, Button, Alert, Platform, alert } from "react-native";
import {useNetInfo} from "#react-native-community/netinfo";
import { MaterialIcons } from '#expo/vector-icons';
export const NoConnection = ({navigation}) => {
const netInfo = useNetInfo();
if (netInfo.isConnected) {
navigation.navigate("Login")
}
return (
<View>
<Text>Type: {netInfo.type}</Text>
<Text>Is Connected? {netInfo.isConnected.toString()}</Text>
</View>
);
}
you will have to use useState hook, set default to true , then if connected update state to false.
import React, { Component,useState } from "react";
import { View, Text, Button, Alert, Platform, alert } from "react-native";
import NetInfo,{useNetInfo} from "#react-native-community/netinfo"
import { MaterialIcons } from '#expo/vector-icons';
export const NoConnection = ({navigation}) => {
const netInfo = useNetInfo();
//declare a isConnected hook with default true
const [isConnected, setConnectedState] = useState(true)
NetInfo.fetch().then(state => {
setConnectedState(state.isConnected)
});
if(isConnected === false) {
console.log("Is connected is", isConnected)
} else {
console.log("Is connected is", isConnected)
}
}
return (
<View>
<Text>Type: {netInfo.type}</Text>
<Text>Is Connected? {netInfo.isConnected.toString()}</Text>
</View>
);
}
you can further learn about hooks and state from the below link.
https://reactjs.org/docs/hooks-state.html

Unable to load provider from react-redux module in react native

I am creating a slide bar, In that, I have used the react-redux library. When I call the class which contains the redux-code, it works fine. I want to show this slide bar after login. Therefore, with conditions (I set a state variable if user login successfully then only this page should get rendered), I tried to call the same file which shows a blank page. I printed the console log. I am able to print all the logs. But with conditions, I am not able to load the data.
I don't know much about react-redux.Can you assist me to resolve this?
My code is,
main.js,
import React, {Component} from 'react';
import {
StyleSheet,
Dimensions,
Platform,
View,
StatusBar,
DrawerLayoutAndroid,
} from 'react-native';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import reducer from '../Redux/reducers';
import { setNavigator, setActiveRoute } from "../Redux/actions";
import DrawerContent from '../Navigation/DrawerContent';
import Toolbar from '../Navigation/Toolbar';
import AppNavigation from '../Navigation/AppNavigation';
import { bgStatusBar, bgDrawer } from '../global.styles';
let store = createStore(reducer);
/* getDrawerWidth Default drawer width is screen width - header width
* https://material.io/guidelines/patterns/navigation-drawer.html
*/
const getDrawerWidth = () => Dimensions.get('window').width - (Platform.OS === 'android' ? 56 : 64);
export default class Main extends Component {
constructor() {
super();
this.drawer = React.createRef();
this.navigator = React.createRef();
}
componentDidMount() {
store.dispatch(setNavigator(this.navigator.current));
}
openDrawer = () => {
this.drawer.current.openDrawer();
};
closeDrawer = () => {
this.drawer.current.closeDrawer();
};
getActiveRouteName = navigationState => {
if (!navigationState) {
return null;
}
const route = navigationState.routes[navigationState.index];
// dive into nested navigators
if (route.routes) {
return getActiveRouteName(route);
}
return route.routeName;
};
render() {
return (
<Provider store={store}>
<DrawerLayoutAndroid
drawerWidth={getDrawerWidth()}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={
() => <DrawerContent closeDrawer={this.closeDrawer} />
}
ref={this.drawer}
>
<View style={styles.container}>
<StatusBar
translucent
animated
/>
<Toolbar showMenu={this.openDrawer} />
<AppNavigation
onNavigationStateChange={(prevState, currentState) => {
const currentScreen = this.getActiveRouteName(currentState);
store.dispatch(setActiveRoute(currentScreen));
}}
ref={this.navigator}
/>
</View>
</DrawerLayoutAndroid>
</Provider>
);
}
}
Login.js
import Main from './main';
render() {
return (
<View>
{this.state.isLoggedIn ?
<Main/>
:
<ChangePassword isUpdatePassword={this.state.isUpdatePassword} callLogin={this.callLogin}/>
);
}
}
If I just call Main class inside render method it works. But It does not work with conditions.

Accessing navigation props - react-navigation

I just have a question regarding react-navigation.
I understand that the navigation props becomes accessible when a screen is rendered from the stacknavigator.
But how do you access the navigation props if the screen is not rendered by the stacknavigator?
Like this:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
StyleSheet,
Text,
View,
} from 'react-native';
import Swiper from 'react-native-swiper';
import Menu from './Menu';
class HomeSwiper extends Component {
static propTypes = {
navigation: PropTypes.object,
};
render() {
return (
<Swiper showsButtons>
<View>
<Menu
navigationProps={this.props.navigation}
/>
</View>
<View>
<Text>Hello Swiper</Text>
</View>
</Swiper>
);
}
}
export default HomeSwiper;
Wherein Menu is:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { AsyncStorage, TouchableOpacity, Text, BackHandler, Alert } from 'react-native';
import { StandardContainerIOS } from '../components/Container';
import { StandardButton } from '../components/Buttons/';
class Menu extends Component {
static propTypes = {
navigation: PropTypes.object,
};
static navigationOptions = ({ navigation }) => {
const { params = {} } = navigation.state;
const headerLeft = (
<TouchableOpacity
onPress={params.handleRedirect ? params.handleRedirect : () => null}
>
<Text>Logout</Text>
</TouchableOpacity>
);
return {
headerLeft,
};
};
constructor(props) {
super(props);
this.state = {
email: '',
petName: [],
numberOfPets: '',
};
}
getInitialState() {
return {
petName: ['No Name'],
};
}
async componentWillMount() {
try {
const value = await AsyncStorage.getItem('email');
if (value !== null) {
// We have data!!
}
} catch (error) {
// Error retrieving data
}
this.props.navigation.setParams({
handleRedirect: this.handlePressLogout,
});
this.getEmail();
BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}
componentWillUnmount() {
BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}
render() {
return (
<StandardContainerIOS>
<StandardButton backgroundColor="#6D4C41" title="View Pet" onPress={this.handleIndexView} />
<StandardButton backgroundColor="#6D4C41" title="Register Pet" onPress={this.handlePressRegisterPets} />
<StandardButton backgroundColor="#6D4C41" title="Logout" onPress={this.handlePressLogout} />
</StandardContainerIOS>
);
}
}
export default Menu;
I've removed the other function definition to cut the post a little shorter. The Menu screen was working fine when it was rendered from the stacknavigator. Im trying to incorporate swiping in my app.
Any suggestions?

JSONparse won't do with Asyncstorage retrieved item

I'm coding a simple app, and I want to store the user info on the device, and include them in a POST request without keep asking the user for them. So I thought: "let's save them on the device!".
I've managed to store them, but when I retrieve them, I just can't figure how to JSONparse it back to a dict.
Here's what I get when I call the AsyncStorage.getItem:
I/ReactNativeJS(31854): ## STORAGE - Data retrieved: [object Object]
And when I try to pass that through JSONparse, I get "JSON Parse error: Unexpected identifier 'undefined'"
Here's my code:
storage.js:
import React, { Component } from 'react';
import {
AsyncStorage,
} from 'react-native';
module.exports = {
save: function(key, data){
//console.log(save key:${key} data:${data} stringify:${JSON.stringify(data)});
try {
AsyncStorage.setItem(key, JSON.stringify(data));
//console.log(Storage.save() key => value, ${key} => ${JSON.stringify(data)});
return true;
} catch(err) {
//console.log(save: ERROR ${err});
return false;
}
},
read: async function(key) {
//console.log(reading key:${key});
try {
var data = await AsyncStorage.getItem(key);
if (data !== null){
//console.log("Storage.read(): " + typeof(JSON.parse(data)) + ":" + JSON.parse(data));
return JSON.parse(data);
}else {
//console.log("Storage.read(): Not found");
return false;
}
} catch (err) {
//console.log('Storage.read(): error: ' + err.message);
return false;
}
},
empty: function(key){
try {
AsyncStorage.setItem(key, '');
//console.log(Storage.empty: cleaning key ${key});
return true;
} catch(err) {
//console.log(Storage.empty: ERROR ${err});
return false;
}
}
}
index.android.js:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
View,
TouchableHighlight,
Alert,
Image,
AsyncStorage,
TextInput,
} from 'react-native';
import { Container, Button, Text } from 'native-base';
import BackgroundImage from './background.js'
var storage = require('./storage.js');
var form_style = require('./formstylesheet.js');
var t = require('tcomb-form-native');
var Form = t.form.Form;
var Person = t.struct({
Nombre: t.String,
Apellido: t.String,
Celular: t.String,
Lote: t.String,
});
var options = {
stylesheet: form_style
};
class UserInfo extends Component {
onPress() {
var value = this.refs.form.getValue();
storage.save('username', JSON.stringify(value.Nombre));
var data = storage.read('username');
}
render() {
return (
<Image source={require('./images/background.jpg')} style={styles.image_container}>
<View style={styles.input_container}>
<Form
ref="form"
type={Person}
options={options}
/>
<TouchableHighlight style={styles.save_button} onPress={this.onPress.bind(this)} underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Guardar</Text>
</TouchableHighlight>
</View>
</Image>
)
}
}
Not sure if everything needed to solve the problem is in here. Please let me know if I'm missing something, or there's more snippets needed.
Thanks in advance!

ReactNative and NativeBase Radio

I've tried to change the radio value in ReactNative App with NativeBase template. I want to get or set value from the radio after click it, exactly checked or not. But couldn't find a way to get or set value to it. Even the radio button never changed on the screen after click. The codes are like as below:
import React, { Component } from 'react';
import { TouchableOpacity, Image, View } from 'react-native';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import {
Container,
Header,
Title,
Content,
Text,
Button,
Icon,
InputGroup,
Input,
List,
ListItem,
Radio, } from 'native-base';
import { openDrawer } from '../../actions/drawer';
import { Col, Row, Grid } from 'react-native-easy-grid';
import styles from './styles';
import dimension from './global';
import Swiper from 'react-native-swiper';
const imgBoy = require('../../../images/icon_boy.png');
const imgGirl = require('../../../images/icon_girl.png');
const {
popRoute,
} = actions;
class SessionPage extends Component {
static propTypes = {
name: React.PropTypes.string,
index: React.PropTypes.number,
list: React.PropTypes.arrayOf(React.PropTypes.string),
openDrawer: React.PropTypes.func,
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
constructor(props) {
super(props);
// console.log(this.props.navigation);
this.state = {
sliderCount : parseInt(this.props.navigation.behavior.length / 5) + 1,
sliderArray : [],
selected : false,
}
this.getSliderArray();
console.log(this.state);
}
getSliderArray() {
for (var i = 0; i < this.state.sliderCount; i++) {
var childArray = [];
for (var j = i * 5; j < 5 * (i + 1); j++) {
if (this.props.navigation.behavior[j] != null){
var unit = this.props.navigation.behavior[j];
unit.selected = true;
childArray.push(unit);
}
}
this.state.sliderArray.push({
index : i,
behaviors : childArray
})
}
}
selectRadio(i, j){
this.state.sliderArray[i].behaviors[j].selected = true;
}
render() {
const { props: { name, index, list } } = this;
return (
<Container style={styles.container}>
<Swiper style={styles.wrapper}
height={dimension.Height - 400}
width={dimension.Width - 40}
showsButtons={false}
showsPagination={true}>
{this.state.sliderArray.map((item, i) =>
<View style={styles.slide1} key={i}>
{item.behaviors.map((subitem, j) =>
<ListItem key={i + "-" + j} style={styles.cardradio}>
<Radio selected={this.state.sliderArray[i].behaviors[j].selected} onPress={() => this.selectRadio(i, j)} />
<Text>{subitem.behaviorName}</Text>
</ListItem>
)}
</View>
)}
</Swiper>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
name: state.user.name,
index: state.list.selectedIndex,
list: state.list.list,
});
export default connect(mapStateToProps, bindAction)(SessionPage);
selectRadio(i, j){
this.state.sliderArray[i].behaviors[j].selected = true; <== This is the problem
}
When you call this.state = something after the component has mounted, it doesn't trigger update method of component life cycle. Hence view will not be updated.
You should be using this.setState() to update your views
this.setState({
slider = something
})
For more info, refer docs
this.setState() is an async method. After you make changes in getSliderArray(), it may not be reflected in immediate console.log
this.getSliderArray();
console.log(this.state);
You can pass callback to this.setState() to perform any action only after state is changed
this.setState({
// new values
}, function() {
// Will be called only after switching to new state
})