I'm fairly new to React Native and was developing an app for myself when the undefined error fired.
Like most of us, I googled away seeing what the problem might be and it seemed to be a common problem, but no fixes worked. I tried arrow functions and .bind but nothing seemed to have worked.
import React, {Fragment} from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
TouchableWithoutFeedback,
Button,
} from 'react-native';
//I'll use the other things I've imported later :-)
const App = () => {
state = {text: 'Hello World'};
return (
<View>
<Text style={styles.titleStyle}>Title Text</Text>
<TouchableWithoutFeedback
onPress={() => (this.setState({
text: 'Goodbye World',
}))}>
<View style={styles.physView}>
<Text style={styles.physTitle}>More Text</Text>
<Text style={styles.physText}>{this.state.text}</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
};
The goal is simply to have the text change to Goodbye World on press but the setState is not a function error fires instead. Eventually, I'd like to have Hello World and Goodbye World switch back and fourth on click but I'm not quite past this error yet.
Thanks in advance and yes, it is dummy text.
You use functional component with state. It doesn't work like that. Functional components can't have setState method.
There are two options:
// Use class syntax
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
text: 'Hello world!',
}
}
onPress = () => {
this.setState({text: 'Bye-bye'});
}
render() {
return (
<View>
<Text style={styles.titleStyle}>Title Text</Text>
<TouchableWithoutFeedback
onPress={this.onPress}>
<View style={styles.physView}>
<Text style={styles.physTitle}>More Text</Text>
<Text style={styles.physText}>{this.state.text}</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
}
};
// Use hooks
import {useState} from 'react'
const App = () => {
const [text, setText] = useState('Hello World');
return (
<View>
<Text style={styles.titleStyle}>Title Text</Text>
<TouchableWithoutFeedback
onPress={() => setText('Goodbye World');}>
<View style={styles.physView}>
<Text style={styles.physTitle}>More Text</Text>
<Text style={styles.physText}>{this.state.text}</Text>
</View>
</TouchableWithoutFeedback>
</View>
);
};
Please try this code:
<TouchableWithoutFeedback onPress={ () => this.setState({ text: 'Goodbye World' }) }>
The problem is that you just call this.setState(...) immediately when the component gets rendered for the first time.
<TouchableWithoutFeedback
onPress={this.setState({
text: 'Goodbye World',
})}>
Notice how this.setState() is executed immediately, but what you want to do is pass a function which can get executed later. This can be done by wrapping the function in another function. So if you try this:
<TouchableWithoutFeedback
onPress={() => { this.setState({
text: 'Goodbye World',
}) }}>
It should behave as expected. All I did was wrap this.setState(...) with an arrow function so it becomes () => { this.setState(...) }
You can't use state with functional component. So try to use React Hooks.
Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.
https://en.reactjs.org/docs/hooks-intro.html
import React, {useState} from 'react';
...
const App = () => {
const [text, setText] = useState('Hello World');
...
<TouchableWithoutFeedback
onPress={() => setText('Bye-bye')}>
...
Related
I'm trying to use Async Storage for a note app, I created a component called task.js as a template for todos, an navigation.js component for nav, and home.js for the main screen all display with <navigation /> inapp.js, I added a funcction to store object value using async storage, but is not working, everytime I hard reload the app everything will be gone but it is not giving me any errors, I don't know where to start
here is my Home.js
import React, {useState} from 'react';
import { Keyboard, KeyboardAvoidingView, Platform, StyleSheet, Text,
TextInput, TouchableOpacity, View, SafeAreaView, ScrollView, Image } from 'react-native';
import Task from '../components/Task';
import AsyncStorage from '#react-native-async-storage/async-storage';
export default function Home({ navigation }) {
const [task, setTask] = useState();
const [taskItems, setTaskItems] = useState([]);
React.useEffect ( () => {
save(taskItems);
}, [taskItems])
React.useEffect (() => {
getsave();
}, [])
const handleAddTask = () => {
Keyboard.dismiss();
setTaskItems([...taskItems, task])
setTask(null);
}
const completeTask = (index) => {
let itemsCopy = [...taskItems];
itemsCopy.splice (index, 1);
setTaskItems(itemsCopy)
}
const save = async taskItems =>{
try {
const savetask = JSON.stringify(taskItems)
await AsyncStorage.setItem('tasksave', savetask)
} catch (e) {
console.log(e);
}
};
const getsave = async () => {
try {
const taskItems = await AsyncStorage.getItem('tasksave');
if (taskItems != null){
setTaskItems(JSON.parse(taskItems));
}
} catch (error) {
console.log(e);
}
};
return (
<SafeAreaView style={styles.container}>
<View style={styles.tasksWrapper}>
<Text style={styles.sectionTitle}>Your stuff:</Text>
<TouchableOpacity onPress={() => navigation.navigate('About')}>
<Text style={styles.about}>About</Text>
</TouchableOpacity>
<ScrollView style={styles.items}>{
taskItems.map((item, index) => {
return (
<View key={index}>
<TouchableOpacity onPress={ () => navigation.navigate("Gas", {item})}>
<Task text={item} navigation={navigation} />
</TouchableOpacity>
<TouchableOpacity onPress={() => completeTask(index)} style={styles.deleteW}>
<Image style={styles.delete} source={require('../components/remove.png')}></Image>
</TouchableOpacity>
</View>
)
})
}
</ScrollView>
</View>
<KeyboardAvoidingView
behavior={Platform.OS === "ios" ? "padding" : "height"}
style={styles.textwrapper}>
<TextInput style={styles.input} placeholder={'message'} value={task} onChangeText={text => setTask(text)}></TextInput>
<TouchableOpacity onPress={() => handleAddTask()}>
<View style={styles.addWrap}>
<Text style={styles.add}>+</Text>
</View>
</TouchableOpacity>
</KeyboardAvoidingView>
</SafeAreaView>
);
}
Here's my Task.js:
import React from "react";
import { View, Text, StyleSheet, Image, TouchableOpacity } from "react-native";
const Task = (props, {navigation}) => {
return (
<View style={styles.item}>
<View style={styles.itemleft}>
<Image style={styles.lightball} source={require('./arabic.png')}></Image>
<Text style={styles.itemtext}>{props.text}</Text>
</View>
<Image style={styles.arrow} source={require('./rightarrow.png')}></Image>
</View>
)
}
const styles = StyleSheet.create({
export default Task;
I hope is a quick read, I took out all the style stuff but this is still kinda long sorry, if you think it has something to do with my app.js or nav.js I can give you those too, I usually slove these bugs on my own but I just have no idea where to begin cause I'm not getting any error messages, thank you
i'm a complete beginner to React Native and i'm trying to add items to flatlist using textinput. i keep constantly getting a TypeError: undefined is not an object (evaluating'_this.setState'). i have edited the code many times and tried to research what i can do, but it still is not working properly. could someone help me and tell me what i need to change? below is my code.
thank you in advance!
import React, { useState, setState } from 'react';
import { View, Text, StyleSheet, FlatList, Alert, TouchableOpacity, TextInput } from 'react-native';
export default function FlatlistComponent({ }) {
const array = [{title: 'ONE'}, {title: 'TWO'}];
const [arrayHolder] = React.useState([]);
const [textInputHolder] = React.useState('');
const componentDidMount = () => {
setState({ arrayHolder: [...array] })
}
const joinData = () => {
array.push({ title : textInputHolder });
this.setState({ arrayHolder: [...array] });
}
const FlatListItemSeparator = () => {
return (
<View
style={{
height: 1,
width: "100%",
backgroundColor: "#607D8B",
}} />
);
}
const GetItem = (item) => {
Alert.alert(item);
}
return (
<View style={styles.MainContainer}>
<TextInput
placeholder="Enter Value Here"
onChangeText={data => this.setState({ textInputHolder: data })}
style={styles.textInputStyle}
underlineColorAndroid='transparent'
/>
<TouchableOpacity onPress={joinData} activeOpacity={0.7} style={styles.button} >
<Text style={styles.buttonText}> Add Values To FlatList </Text>
</TouchableOpacity>
<FlatList
data={arrayHolder}
width='100%'
extraData={arrayHolder}
keyExtractor={(index) => index.toString()}
ItemSeparatorComponent={FlatListItemSeparator}
renderItem={({ item }) => <Text style={styles.item} onPress={GetItem.bind(this, item.title)} > {item.title} </Text>}
/>
</View>
);
}
So I see you're trying to use functional components here.
State variables can be rewritten like this
const [arrayHolder, setArrayHolder] = useState([]);
const [textInputHolder, setTextInputHolder] = useState('');
componentDidMount is used in class components and can be rewritten like this for functional components
import React, { useState, useEffect } from 'react';
useEffect(()=>{
setArrayHolder(array)
}, [])
Function joinData can be re-written like this.
const joinData = () => {
array.push({ title : textInputHolder });
setArrayHolder(array)
}
About the text not showing up. You're using this.setState in the onChangeText event. It is a functional component and this won't work in a functional component.state variables are declared and set using the useState hook in a functional component.
You should rewrite the onChangeText event like this.
<TextInput
placeholder="Enter Value Here"
onChangeText={data => setTextInputHolder(data)}
style={styles.textInputStyle}
underlineColorAndroid='transparent'
/>
I think this'll solve your problem
I've tried a few methods to get setState() to update the value of state. Currently the text in the <TextInput> changes, but the value in this.state doesn't change.
I have the console.log in the right place, I've tried writing external functions, I've messed around with the variable's names but nothing seems to work.
import * as React from 'react';
import { View, Text, TextInput, TouchableHighlight, Dimensions, StyleSheet } from "react-native";
import PropTypes from "prop-types";
class EditNote extends React.Component{
constructor(props){
super(props)
this.state = {
title: '',
text: '',
id: ''
}
}
// TODO: Change textboxes to match the props from the NoteList
static getDerivedStateFromProps(props){
return(
{...props.route.params}
)
}
render(){
return(
<View style={s.container}>
<View style={s.titleContainer}>
<Text style={s.titleText}>Edit Note</Text>
<View style={{flex: 1}}/>
</View>
<View style={s.inputContainer}>
<TextInput
style={{...s.input, ...s.titleInput}}
autoCapitalize='words'
keyboardAppearance='dark'
placeholderTextColor='#DDD'
onChangeText={(title) => { this.setState({title: title}, () => console.log(this.state)) }}
defaultValue={this.state.title}
/>
<TextInput
style={{...s.input, ...s.textInput}}
autoCapitalize='sentences'
keyboardAppearance='dark'
placeholderTextColor='#DDD'
multiline
onChangeText={(text) => { this.setState({text: text}, () => console.log(this.state)) }}
defaultValue={this.state.text}
/>
</View>
<View style={s.buttonContainer}>
<TouchableHighlight
style={s.backButton}
onPress={() => this.props.nav.navigate('NoteListView')}
underlayColor='#300030'
>
<Text style={s.buttonText}>Cancel</Text>
</TouchableHighlight>
<TouchableHighlight
style={s.addButton}
onPress={() => {
console.log(this.state.note)
this.props.nav.navigate('NoteListView', {note: this.state, mode: 'edit'})
}}
underlayColor='#300030'
>
<Text style={s.buttonText}>Edit</Text>
</TouchableHighlight>
</View>
</View>
)
}
}
export default EditNote
I just realized that this is a problem with two parts.
The first problem is that props.route.params is unaffected by subsequent render() calls. This means that even if you re-render the component, the same initial properties are used.
The second is getDerivedStateFromProps(). Every time the render function is called it calls getDerivedStateFromProps() right before it which sets the state to the initial route parameters.
This problem can be fixed by:
Clearing the initial route parameters in the render function after their initial use. Something a little like this at the beginning of the render()function will work. this.props.route.params = undefined
Using an if statement and a variable in state to regulate when the props should update the state.
Refactor the code to make use of the props
Option 3 is how things should be correctly done but the best solution depends on how your code works.
I'm a beginner in React Native trying to test out TouchableOpacity. I keep getting this error code 'Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment <>...? (16:4)'
The issue seems to be at the opening TouchableOpacity tag.
I've already tried putting fragments around it but it didn't work does anyone know how I fix this??
import React from 'react';
import { Text, StyleSheet, View, Button, TouchableOpacity } from 'react-
native';
const HomeScreen = () => {
return (
<View>
<Text style={styles.text}>Sup boiz</Text>
<Button
onPress={() => console.log('Button pressed')}
title="Go to components demo"
/>
<TouchableOpacity onPress={ () => console.log('List Pressed')>
<Text>Go to List demo</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
text: {
fontSize: 30
}
});
export default HomeScreen;
<TouchableOpacity onPress={ () => console.log('List Pressed')}>
<Text>Go to List demo</Text>
</TouchableOpacity>
Simple syntax error. It should be onPress={ () => console.log('List Pressed')}
You missed }
I've written a click handler to resolve a download button to the google play store URL.
The problem is that when the page loads, the URL is immediately visited.
The click handler is nested inside an onPress attribute, and I don't press anything, so I'm struggling to understand why this would be happening.
Any help would be appreciated!
OpenURL.js:
'use strict';
import React, {
Component,
PropTypes,
Linking,
StyleSheet,
Text,
TouchableNativeFeedback,
TouchableHighlight,
View
} from 'react-native';
class OpenURLButton extends Component {
constructor(props) {
super(props);
}
handleClick(url) {
console.log(url);
console.log('handling click! this is : ');
console.dir(this);
Linking.canOpenURL(this.props.url).then(supported => {
if (supported) {
Linking.openURL(this.props.url);
} else {
console.log('Don\'t know how to open URI: ' + this.props.url);
}
});
}
render() {
console.log('logging "this" inside render inside OpenURL.js:');
console.dir(this);
return (
<TouchableHighlight onPress={this.handleClick(this.props.appStoreUrl)}>
<Text>Download {this.props.appStoreUrl}</Text>
</TouchableHighlight>
);
}
}
OpenURLButton.propTypes = {
url: React.PropTypes.string,
}
export default OpenURLButton;
Inventory.js:
<ScrollView>
<View style={styles.ImageContainer}>
<Image style={styles.ImageBanner} source={{uri: selectedInventory.bannerImage}} />
</View>
<View style={styles.ListGridItemCaption}>
<Image style={[styles.ImageThumb, styles.ImageGridThumb]} source={{uri: selectedInventory.thumbImage}} />
<Text style={styles.Text} key="header">{name}</Text>
</View>
<View>
<Text>{selectedInventory.description}</Text>
<OpenURLButton url={selectedInventory.appStoreUrl}/>
</View>
</ScrollView>
Change:
<TouchableHighlight onPress={this.handleClick(this.props.appStoreUrl)}>
<Text>Download {this.props.appStoreUrl}</Text>
</TouchableHighlight>
To:
<TouchableHighlight onPress={() => {this.handleClick(this.props.appStoreUrl)}}>
<Text>Download {this.props.appStoreUrl}</Text>
</TouchableHighlight>
With the change you are creating anonymous function that are calling on "your" method. This will work.