I have react-native 0.30 installed and I have troubles to update and execute an old piece of code i found on internet.
Here is the old rn code :
"use strict";
var React = require("react-native");
var {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
AsyncStorage,
} = React;
var ReactProject = React.createClass({
componentDidMount: function() {
AsyncStorage.getItem("myKey").then((value) => {
this.setState({"myKey": value});
}).done();
},
getInitialState: function() {
return { };
},
render: function() {
return (
<View style={styles.container}>
<Text style={styles.saved}>
{this.state.myKey}
</Text>
<View>
<TextInput
style={styles.formInput}
onChangeText={(text) => this.saveData(text)}
value="" />
</View>
<Text style={styles.instructions}>
Type something into the text box. It will be saved to
device storage. Next time you open the application, the saved data
will still exist.
</Text>
</View>
);
},
saveData: function(value) {
AsyncStorage.setItem("myKey", value);
this.setState({"myKey": value});
}
});
var styles = StyleSheet.create({
container: {
padding: 30,
flex: 1,
justifyContent: "center",
alignItems: "stretch",
backgroundColor: "#F5FCFF",
},
formInput: {
flex: 1,
height: 26,
fontSize: 13,
borderWidth: 1,
borderColor: "#555555",
},
saved: {
fontSize: 20,
textAlign: "center",
margin: 10,
},
instructions: {
textAlign: "center",
color: "#333333",
marginBottom: 5,
marginTop: 5,
},
});
AppRegistry.registerComponent('ReactProject', () => ReactProject);
And here is what I've done to update it :
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
"use strict";
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
TextInput,
AsyncStorage,
View
} from 'react-native';
class pulps extends Component {
componentDidMount() {
AsyncStorage.getItem("myKey").then((value) => {
this.setState({"myKey": value});
}).done();
}
getInitialState() {
return { };
}
render() {
return (
<View style={styles.container}>
<Text style={styles.saved}>
{this.state.myKey}
</Text>
<View>
<TextInput
style={styles.formInput}
onChangeText={(text) => this.saveData(text)}
value="" />
</View>
<Text style={styles.instructions}>
Type something into the text box. It will be saved to
device storage. Next time you open the application, the saved data
will still exist.
</Text>
</View>
);
}
saveData(value) {
return (
AsyncStorage.setItem("myKey", value);
this.setState({"myKey": value});
);
}
}
var styles = StyleSheet.create({
container: {
padding: 30,
flex: 1,
justifyContent: "center",
alignItems: "stretch",
backgroundColor: "#F5FCFF",
},
formInput: {
flex: 1,
height: 26,
fontSize: 13,
borderWidth: 1,
borderColor: "#555555",
},
saved: {
fontSize: 20,
textAlign: "center",
margin: 10,
},
instructions: {
textAlign: "center",
color: "#333333",
marginBottom: 5,
marginTop: 5,
},
});
AppRegistry.registerComponent('pulps', () => pulps);
But I have the following error on the screen of my ios-simulator when I press cmd+R :
SyntaxError /Users/***/Documents/pulps/index.ios.js: Unexpected token(53:44)
Could you pls tell me where I am wrong ?
By the way is it better for that kind of script to use plain Javascript or ES6 ?
Thank you !
You've just an error in the method saveData when using "return" in a way that isn't allowed.
Your code:
saveData(value) {
return (
AsyncStorage.setItem("myKey", value);
this.setState({"myKey": value});
);
}
You can't use "return" here when calling two void methods. Just change it like this:
saveData(value) {
AsyncStorage.setItem("myKey", value);
this.setState({"myKey": value});
}
Related
Android app crashes when I open build app. It's happens only when I build app react native async storage. On iOS & Android emulators it's working stability. Help me please!
At first I thought that the problem was that I did not use JSON, but it turned out that I did not. JOHN tried, but nothing came of it. Maybe I am not saving correctly in Async Storage?
import React, { useState, useEffect } from 'react'
import { View, TextInput, StyleSheet, TouchableOpacity, ScrollView } from 'react-native'
import Icon from 'react-native-vector-icons/Octicons'
import BackNavbar from '../components/BackNavbar'
import { colors } from '../theme/theme'
import AsyncStorage from '#react-native-community/async-storage'
import GoalCard from '../components/GoalCard'
export default GoalScreen = ({ navigation }) => {
const STORAGE_KEY = '#data'
function goBack() {
navigation.goBack()
}
const [ goal, setGoal ] = useState([])
const [ goalScore, setGoalScore ] = useState()
const [ goalName, setGoalName ] = useState('')
const addGoal = () => {
setGoal([
... goal,
{
id: Date.now(),
text: goalName,
score: goalScore,
}
])
setGoalName('')
setGoalScore('')
}
const saveData = async (dataSave) => {
try {
await AsyncStorage.setItem(STORAGE_KEY, dataSave)
} catch (e) {
alert('Failed to save the data to the storage')
}
}
const loadData = async () => {
try {
const json = await AsyncStorage.getItem(STORAGE_KEY) || JSON.stringify([])
const loadData = JSON.parse(json)
if (loadData != null) {
setGoal(loadData)
alert(loadData.map())
}
} catch (e) {
alert('Failed to load the data to the storage')
}
}
useEffect(() => {
loadData()
}, [])
useEffect(() => {
saveData(JSON.stringify(goal))
}, [goal])
return (
<View style={styles.container}>
<BackNavbar title='Goals' back={goBack} />
<ScrollView>
{ goal.map( item => <GoalCard key={item.id} {... item} /> ) }
</ScrollView>
<View style={styles.inputView}>
<TextInput
keyboardType = "number-pad"
style={styles.inputTextScore}
value={goalScore}
onChangeText={score => setGoalScore(score)}
/>
<TextInput
style={styles.inputText}
value={goalName}
onChangeText={name => setGoalName(name)}
/>
<TouchableOpacity
style={styles.inputButton}
onPress={addGoal}
>
<Icon name="plus" size={26} color={colors.LIGHT_COLOR} />
</TouchableOpacity>
</View>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'flex-start',
},
inputView: {
marginTop: 15,
flexDirection: 'row',
width: '80%',
marginBottom: 15,
},
inputText: {
width: '62%',
height: 50,
paddingHorizontal: '5%',
right: 5,
borderRadius: 15,
backgroundColor: '#f2f2f2',
borderColor: colors.BORDER_COLOR,
color: colors.SECOND_COLOR,
borderWidth: 1,
fontSize: 20,
elevation: 3,
fontSize: 16,
},
inputTextScore: {
width: '20%',
height: 50,
marginRight: 10,
paddingHorizontal: '5%',
right: 5,
borderRadius: 15,
backgroundColor: '#f2f2f2',
borderColor: colors.BORDER_COLOR,
borderWidth: 1,
fontSize: 20,
elevation: 3,
color: colors.SECOND_COLOR,
fontWeight: '500',
},
inputButton: {
alignItems: 'center',
justifyContent: 'center',
paddingHorizontal: 15,
paddingVertical: 10,
borderRadius: 50,
backgroundColor: colors.MAIN_COLOR,
left: 5,
}
})
I am new to react native this is my first attempt in react native I was following a sample tutorial for the basic understanding of the code and other things I am following this raywenderlich's propertyfinder example, while implementing the first navigation example I am facing this issue:
undefined is not a function (evaluating 'this.props.renderScene(route,this)')
in my android device(Samsung J7) which I am using to run the app
Here is my index.android.js
'use strict';
var React = require('react');
var ReactNative = require('react-native');
var SearchPage = require('./SearchPage');
var styles = ReactNative.StyleSheet.create({
text: {
color: 'black',
backgroundColor: 'white',
fontSize: 30,
margin: 80
},
container: {
flex: 1
}
});
class PropertyFinderApp extends React.Component {
render() {
return (
<ReactNative.Navigator
style={styles.container}
renderScene={this.renderScene}
initialRoute={{
component: SearchPage,
index:0,
title:"home"
}}/>
);
}
}
ReactNative.AppRegistry.registerComponent('PropertyFinder', function() { return PropertyFinderApp });`
and the SearchPage.js file(the other component which I am using):
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
TextInput,
View,
TouchableHighlight,
ActivityIndicator,
Image
} from 'react-native';
var styles = StyleSheet.create({
description: {
marginBottom: 20,
fontSize: 18,
textAlign: 'center',
color: '#656565'
},
container: {
padding: 30,
marginTop: 65,
alignItems: 'center'
},
flowRight: {
flexDirection: 'row',
alignItems: 'center',
alignSelf: 'stretch'
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
button: {
height: 36,
flex: 1,
flexDirection: 'row',
backgroundColor: '#48BBEC',
borderColor: '#48BBEC',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
alignSelf: 'stretch',
justifyContent: 'center'
},
searchInput: {
height: 36,
padding: 4,
marginRight: 5,
flex: 4,
fontSize: 18,
borderWidth: 1,
borderColor: '#48BBEC',
borderRadius: 8,
color: '#48BBEC'
}
});
export default class SearchPage extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.description}>
Search for houses to buy!
</Text>
<Text style={styles.description}>
Search by place-name, postcode or search near your location.
</Text>
<View style={styles.flowRight}>
<TextInput
style={styles.searchInput}
placeholder='Search via name or postcode'/>
<TouchableHighlight style={styles.button}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Go</Text>
</TouchableHighlight>
</View>
<TouchableHighlight style={styles.button}
underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Location</Text>
</TouchableHighlight>
</View>
);
}
}
module.exports = SearchPage;
I have no idea what I am doing wrong since I am a beginner in this any help will be appreciated, thanx in advance.
You for got to write renderScene function, see following example:
<ReactNative.Navigator
...
renderScene={this.renderScene.bind(this)} />
renderScene(route, navigationOperations, onComponentRef) {
switch(route.index) {
case 0:
return <SearchPage />
}
}
I'm reading Learning React Native by Bonnie Eisenman and am having trouble with the WeatherProject tutorial in chapter 3. When the app loads in the iOS simulator, it appears to be rendering the contents of Forecast.js but taking up the whole display without anything from WeatherProject.js
Here is my code:
index.ios.js
import {
AppRegistry,
} from 'react-native';
import WeatherProject from './WeatherProject';
AppRegistry.registerComponent('WeatherProject', () => WeatherProject);
WeatherProject.js
import React, {
Component,
} from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
} from 'react-native';
var Forecast = require('./Forecast');
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#4D4D4D'
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10
},
input: {
fontSize: 20,
borderWidth: 2,
height: 40
}
});
var WeatherProject = React.createClass({
getInitialState() {
return {
zip: '',
forecast: {
main: 'Clouds',
description: 'few clouds',
temp: 45.7
}
}
},
_handleTextChange(event) {
console.log(event.nativeEvent.text);
this.setState({
zip: event.nativeEvent.text
});
},
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
You input {this.state.zip}.
</Text>
<Forecast
main={this.state.forecast.main}
description={this.state.forecast.description}
temp={this.state.forecast.temp}/>
<TextInput
style={styles.input}
returnKeyType="go"
onSubmitEditing={this._handleTextChange}/>
</View>
);
}
});
module.exports = WeatherProject;
Forecast.js
import React, {
Component,
} from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
var styles = StyleSheet.create({
bigText: {
flex: 2,
fontSize: 20,
textAlign: 'center',
margin: 10,
color: '#FFFFFF'
},
mainText: {
flex: 1,
fontSize: 16,
textAlign: 'center',
color: '#FFFFFF'
}
});
var Forecast = React.createClass({
render() {
return (
<View>
<Text style={styles.bigText}>
{this.props.main}
</Text>
<Text style={styles.mainText}>
Current conditions: {this.props.description}
</Text>
<Text style={styles.bigText}>
{this.props.temp}°F
</Text>
</View>
);
}
});
module.exports = Forecast;
The expected outcome looks like this (from the book):
But my actual outcome is this:
And here is the view debug hierarchy:
Any help at all would be greatly appreciated.
Add this style in Forecast:
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
then add the style into the View:
<View styles={style.container}>
I am learning react native for the first time for developing android app not IOS one and I was learning from Building a Simple ToDo App With React Native and Firebase tutorial from youtube.But I am getting an error while trying to add items. I get following error
Firebase.push failed: first argument contains an invalid key($$typeof) in property 'restaurant.restaurant_name.targetInst._nativeParent._currentElement'.keys must be non-empty strings and cant contain ".","#","$","/","["
What might be creating this issue?
import React, { Component } from 'react';
import Firebase from 'firebase';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableHighlight,
TextInput,
ListView
} from 'react-native';
class foodOrderSystem extends Component {
constructor(props){
super(props);
const firebaseRef = new Firebase('foodordersystem.firebaseio.com');
console.log(firebaseRef);
this.itemRef = firebaseRef.child('restaurant');
this.state = {
newRestaurant:'',
// estimated_delivery:'',
// description:'',
restaurantSource: new ListView.DataSource({rowHasChanged: (row1,row2) => row1 !== row2})
};
this.restaurant = [ ];
}
componentDidMount() {
this.itemRef.on('child_added', (snap) => {
this.restaurant.push({
id:snap.key(),
text:snap.val()
});
this.setState({
restaurantSource:this.state.restaurantSource.cloneWithRows(this.restaurant)
});
});
this.itemRef.on('child_removed', (snap) => {
this.restaurant = this.restaurant.filter((x) => x.id !== snap.key());
this.setState({
restaurantSource:this.state.restaurantSource.cloneWithRows(this.restaurant)
});
});
}
addRestaurant(){
if(this.state.newRestaurant !== ''){
this.itemRef.push({
restaurant_name: this.state.newRestaurant
});
this.setState({ newRestaurant:''});
}
}
removeRestaurant(rowData){
this.itemRef.child(rowData.id).remove();
}
render() {
return (
<View style={styles.appContainer}>
<View style={styles.titleView}>
<Text style={styles.titleText}>
foodOrderSystem
</Text>
</View>
<View style={styles.inputcontainer}>
<TextInput
style={styles.input}
onChange={(text) => this.setState({newRestaurant:text})}
value={this.state.newRestaurant} />
<TouchableHighlight
style={styles.button}
onPress={ () => this.addRestaurant() }
underlayColor="#00ffff">
<Text style={styles.btnText}>Add</Text>
</TouchableHighlight>
</View>
<ListView
dataSource={this.state.restaurantSource}
renderRow={this.renderRow.bind(this)} />
</View>
);
}
renderRow(rowData){
return(
<TouchableHighlight
underlayColor="#dddddd"
onPress={() => this.removeRestaurant(rowData)}>
<View>
<View style={styles.row}>
<Text style={styles.todoText}>{rowData.text}</Text>
</View>
<View style={styles.separator} />
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
appContainer:{
flex: 1
},
titleView:{
backgroundColor: '#48afdb',
paddingTop: 30,
paddingBottom: 10,
flexDirection: 'row'
},
titleText:{
color: '#fff',
textAlign: 'center',
fontWeight: 'bold',
flex: 1,
fontSize: 20,
},
inputcontainer: {
marginTop: 5,
padding: 10,
flexDirection: 'row'
},
button: {
height: 36,
flex: 2,
flexDirection: 'row',
backgroundColor: '#48afdb',
justifyContent: 'center',
color: '#FFFFFF',
borderRadius: 4,
},
btnText: {
fontSize: 18,
color: '#fff',
marginTop: 6,
},
input: {
height: 36,
padding: 4,
marginRight: 5,
flex: 4,
fontSize: 18,
borderWidth: 1,
borderColor: '#48afdb',
borderRadius: 4,
color: '#48BBEC'
},
row: {
flexDirection: 'row',
padding: 12,
height: 44
},
separator: {
height: 1,
backgroundColor: '#CCCCCC',
},
todoText: {
flex: 1,
},
});
AppRegistry.registerComponent('foodOrderSystem', () => foodOrderSystem);
Here is the attachment of error
I am new to react native. And I would like to create dynamic color of my application on the basis of selection.
/**
* Sample React Native App
* https://github.com/facebook/react-native
* #flow
*/
import React, {
AppRegistry,
Component,
StyleSheet,
Text,
Image,
NavigatorIOS,
AlertIOS,
ListView,
ScrollView,
TouchableHighlight,
View
} from 'react-native';
import {
times,
uniqueId
} from 'lodash';
var Accordion = require('react-native-accordion/src/index.js');
var my = '#eee';
class AwesomeProject extends Component {
render() {
return (
<View style = {styles.group} >
<NavigatorIOS style = {styles.group}
initialRoute = {{
component: AccordionList,
title: 'Color Selector',
rightButtonIcon: require('./img/a.png'),
onRightButtonPress: () => {
AlertIOS.alert(
'Select Color',
null, [{
text: 'Red',
onPress: () =>setColor( 'red'),
}, {
text: 'Blue',
onPress: () => setColor( 'blue'),
}]
);
}
}
}
barTintColor = "#0391D7"
titleTextColor = "#fff"
tintColor = '#fff' />
<View style = {styles.line}/>
</View>
);
}
}
setColor = function(color){
if(color == 'blue')
my = '#eee';
else
my = '#aaa';
}
const AccordionList = React.createClass({
getInitialState() {
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2
});
return {
dataSource: ds.cloneWithRows(times(6, uniqueId.bind(null, 'ball_'))),
};
},
render() {
return (
<View style = {{flex: 1}} >
<ListView dataSource = {this.state.dataSource}
renderRow = {this._renderRow}
/>
</View>
);
},
_renderHeader() {
return ( <View style = { styles.listView } >
<Image style = {styles.icon}
source = {require('./img/1.jpg')}/>
<Text> Click to Expand {my}< /Text>
</View>
);
},
_renderContent() {
return ( <View style = {styles.container} >
<Text style = {styles.welcome} >
{
'greeting'
}
Welcome to React Native!
</Text>
<Text style = {
styles.instructions
} >
To get started, edit index.ios.js
</Text>
<Text style = {
styles.instructions
} >
Press Cmd + R to reload, {
'\n'
}
Cmd + D or shake
for dev menu
</Text>
</View>
);
},
_renderRow(rowData) {
return ( <Accordion header = {
this._renderHeader()
}
content = {
this._renderContent()
}
duration = {
300
}
easing = "easeOutCubic" />
);
}
});
const styles = StyleSheet.create({
icon: {
height: 20,
width: 20,
alignItems: 'flex-end',
borderWidth: 1
},
listView: {
alignItems: 'flex-end',
paddingTop: 15,
paddingRight: 15,
paddingLeft: 15,
paddingBottom: 15,
borderBottomWidth: 1,
borderBottomColor: my,
backgroundColor: my,
},
line: {
backgroundColor: '#bbbbbb',
height: StyleSheet.hairlineWidth,
},
container: {
flex: 1,
borderWidth: 1,
justifyContent: 'center',
alignItems: 'flex-end',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#3333f3',
marginBottom: 5,
},
group: {
backgroundColor: 'white',
flex: 1
},
groupSpace: {
height: 15,
padding: 10
},
});
const styles_a = StyleSheet.create({
icon: {
height: 30,
width: 30
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
line: {
backgroundColor: '#bbbbbb',
height: StyleSheet.hairlineWidth,
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#3333f3',
marginBottom: 5,
},
listView: {
alignItems: 'flex-start',
paddingTop: 15,
paddingRight: 15,
paddingLeft: 15,
paddingBottom: 15,
borderBottomWidth: 1,
borderBottomColor: my,
backgroundColor: '#fafafa',
},
group: {
backgroundColor: 'white',
flex: 1,
padding: 10
},
groupSpace: {
height: 15,
padding: 10
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
Whenever I select a new color and alert it, it shows me the color selection but, doesn't update the background color of my list.
Any idea what I am doing wrong.
Try this:
Instead of storing the color in a global variable, you should store it in the component's state. If you don't know what state means in React, consider reading this article.
I see you call a setColor function to change the variable my. Instead you could call
this.setState({currentColor: 'red'})
and then in a render() method, you could append it to an array to overwrite the default style:
<SomeComponent style={[styles.myStyle, {backgroundColor: this.state.currentColor}]}/>
The point of doing this is that setState triggers a new UI rendering.