Unexpected token, expected; When calling a function in react native - react-native

I am trying to call a function when a button is pressed.
After I add the function, it errors out with the Unexpected token error.
I followed instructions from all previous similar questions but it doesn't solve my case. Please help.
_handlePress: function() {
console.log("Butto GO!")
}
export default class fun extends Component {
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={() => this._handlePress()}>
<Image style={{width: 50, height: 50}} source={require('./go.png')} />
</TouchableHighlight>
</View>
);
}
}
Also, Should the called function be defined before the default class?

Put the function behind render, after the class and I don't know if u do test : function() it works there so try my example and give feedback
export default class fun extends Component {
_handlePress() {
console.log("Butto GO!")
}
render() {
return (
<View style={styles.container}>
<TouchableHighlight onPress={() => this._handlePress()}>
<Image style={{width: 50, height: 50}} source={require('./go.png')} />
</TouchableHighlight>
</View>
);
}
}
or if you want to do behind the export class you can use _handlePress() instead of this._handlePress() and it should work!
Example:
'use strict';
import React, {Component} from 'react';
import {View,Text,TouchableOpacity,Alert,Dimensions} from 'react-native';
const windows = Dimensions.get('window');
export default class Feed extends Component {
_test(){
Alert.alert("Test");
console.log("It worked!");
}
render() {
return (
<View style={{flex: 1}}>
<TouchableOpacity onPress={() => this._test()}>
<Image source={require('../image/2.jpg')} style={{height: windows.height, width: windows.width, }} />
</TouchableOpacity>
</View>
);
}
}

Related

Invalid Hook Call - React Native

So, I'm trying to use Hooks in React Native but I'm very new to React Native and I don't know how to properly use Hooks in Class and Function components. But in this project, I'm using the Class component but I'm getting an error of invalid hook call, so how do I turn this hook for the function component into the class component.
This is my code:
export default class Home extends Component {
render() {
let [fontsLoaded, error] = useFonts({
Raleway_100Thin,
Raleway_100Thin_Italic,
Raleway_200ExtraLight,
Raleway_200ExtraLight_Italic,
Raleway_300Light,
Raleway_300Light_Italic,
Raleway_400Regular,
Raleway_400Regular_Italic,
Raleway_500Medium,
Raleway_500Medium_Italic,
Raleway_600SemiBold,
Raleway_600SemiBold_Italic,
Raleway_700Bold,
Raleway_700Bold_Italic,
Raleway_800ExtraBold,
Raleway_800ExtraBold_Italic,
Raleway_900Black,
Raleway_900Black_Italic,
});
if (!fontsLoaded) {
return <AppLoading />;
}
return (
<View style={styles.container}>
{/* TITLE */}
<Text style={styles.title}>MALIGAYANG PAGDATING!</Text>
<Text style={styles.subtitle}>RECENTLY VIEWED</Text>
</View>
);
}
}
You can't use hooks inside of a class component. See the Hooks FAQ on the React documentation.
Use this way like
import React from 'react';
import { View, Text } from 'react-native';
import AppLoading from 'expo-app-loading';
import { useFonts, Inter_900Black } from '#expo-google-fonts/inter';
export default function App() {
let [fontsLoaded] = useFonts({
Inter_900Black,
});
if (!fontsLoaded) {
return <AppLoading />;
}
return (
<View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
<Text style={{ fontFamily: 'Inter_900Black', fontSize: 40 }}>Inter Black</Text>
</View>
);
}
Details Here also you can try this way too Here
You cannot use hooks inside a class component. Hooks was designed for functional component only. You can modify your class based component to functional based like below and use it.
// Imports
function Home() {
const [fontsLoaded, error] = useFonts({
Raleway_100Thin,
Raleway_100Thin_Italic,
Raleway_200ExtraLight,
Raleway_200ExtraLight_Italic,
Raleway_300Light,
Raleway_300Light_Italic,
Raleway_400Regular,
Raleway_400Regular_Italic,
Raleway_500Medium,
Raleway_500Medium_Italic,
Raleway_600SemiBold,
Raleway_600SemiBold_Italic,
Raleway_700Bold,
Raleway_700Bold_Italic,
Raleway_800ExtraBold,
Raleway_800ExtraBold_Italic,
Raleway_900Black,
Raleway_900Black_Italic,
});
return fontsLoaded ? (
<View style={styles.container}>
{/* TITLE */}
<Text style={styles.title}>MALIGAYANG PAGDATING!</Text>
<Text style={styles.subtitle}>RECENTLY VIEWED</Text>
</View>
) : (
<AppLoading />
);
}
export default Home;

How to change text in sibling component in react-native?

I have an 'OutputBox' component and want to change the text being displayed in the component when I click a button.
I've read about props and state and i can't seem to get them working the way i need them too. I just started react-native and have a heavy background c++. I thought i could just declare a variable, 'text' in the 'OutputBox' component and then call a 'setOutputBoxText' function and change the 'text' var. Getters and Setters paradigm. I just cant wrap my head around how to use props to 'pass args' to components and the such.
export default class HelloWorldApp extends Component {
render() {
return (
<View style={{ flex: 1, alignItems: "flex-end" }}>
<CustomButton
text="N"
onPress={() => {
OutputBox.setOutputBox('You head North');
alert("You head North");
}}
/>
<OutputBox></OutputBox>
</View>
);
}
}
class CustomButton extends Component {
render() {
const { text, onPress} = this.props;
return (
<TouchableOpacity style={styles.buttonStyle}
onPress={() => onPress()}
>
<Text style={styles.textStyle}>{text}</Text>
</TouchableOpacity>
);
}
}
class OutputBox extends Component {
constructor( props ) {
super( props );
var displayText = 'Hello Traveller';
}
setOutputBox( newText ){
displayText = newText;
}
render() {
return (
<View style={ styles.outputBox }>
<Text>{this.displayText}</Text>
</View>
);
}
}
I would expect to be able to do something similar to what i have, however i just keep getting a typeError: OutputBox.setOutputBox is not a function. I know this is the wrong paradigm for react-native. I can't seem to wrap my head around doing something like this with props and state.
UPDATE: I no longer get the error typeError: OutputBox.setOutputBox is not a function. Now, the OutputBox just doesn't display anything. How I do I get the <Text/> component of the OutputBox to change and display.
Here is the correct way to do it.
export default class HelloWorldApp extends Component {
constructor( props ) {
super( props );
this.state={
displayText : 'Hello Traveller',
}
}
render() {
return (
<View style={{ flex: 1, alignItems: "flex-end" }}>
<CustomButton
text="N"
onPress={() => {
this.setState({displayText:'You head North'})
}}
/>
<OutputBox text={this.state.displayText}/>
</View>
);
}
}
class CustomButton extends Component {
render() {
const { text, onPress} = this.props;
return (
<TouchableOpacity style={styles.buttonStyle}
onPress={() => onPress()}
>
<Text style={styles.textStyle}>{text}</Text>
</TouchableOpacity>
);
}
}
class OutputBox extends Component {
render() {
return (
<View style={ styles.outputBox }>
<Text>{this.props.displayText}</Text>
</View>
);
}
}
I just removed the OutputBox component and put a <Text> component in there. I realized i didn't need the OutputBox component, since it's only purpose was to display text. This is what i ended up with
export default class HelloWorldApp extends Component {
constructor( props ) {
super( props );
this.state={
displayText : 'Hello Traveller',
}
}
render() {
return (
<View style={{ flex: 1, alignItems: "flex-end" }}>
<CustomButton
text="N"
onPress={() => {
this.setState({displayText:'You head North'})
}}
/>
<Text>{this.state.displayText}</Text>
</View>
);
}
}
class CustomButton extends Component {
render() {
const { text, onPress} = this.props;
return (
<TouchableOpacity style={styles.buttonStyle}
onPress={() => onPress()}
>
<Text style={styles.textStyle}>{text}</Text>
</TouchableOpacity>
);
}
}

React Native - Is not a function - Is Undefined

I have the following code in React Native
import React from "react";
import {
StyleSheet,
Text,
View,
Button,
TextInput,
Image,
ScrollView
} from "react-native";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
apiData: [],
};
this.getButton();
}
deleteButton(Id){
fetch("http://192.168.2.22:9090/usuario/" + (Id), {
method: "DELETE"
})
.then(responseData => {
console.log(responseData.rows);
})
.done();
this.dataId = null;
}
render() {
const data = this.state.apiData;
let dataDisplay = data.map(function(jsonData) {
return (
<View style={styles.lista} key={jsonData.id}>
<View style={styles.bordeLista}>
<View style={styles.fila}>
<View style={styles.contenedorfoto}>
<Image
style={styles.foto}
source={require("./img/login.png")}
/>
</View>
<View style={styles.datos}>
<Text>Nombre: {jsonData.nombre}</Text>
<Text>E-mail: {jsonData.email}</Text>
<Text>Telefono: {jsonData.telefono}</Text>
</View>
</View>
<View style={styles.fila}>
<View style={styles.contenedorboton}>
<View style={styles.botoniz}>
<Button title="Modificar" onPress={() => {}} />
</View>
<View style={styles.botonde}>
<Button
title="Eliminar"
onPress={() => this.deleteButton(jsonData.Id)}
color="#ee4c4c"
/>
</View>
</View>
</View>
</View>
</View>
);
});
return (
<Text style={styles.titulo}>Usuarios desde BD MySQL</Text>
<ScrollView>
<View>{dataDisplay}</View>
</ScrollView>
</View>
);
}
}
And I want to call deleteButton() from this button
<Button
title="Eliminar"
onPress={() => this.deleteButton(jsonData.Id)}
color="#ee4c4c"
/>
But I get the following error, That the method is not a function and that it is not defined.
Error
How could I use the function? And I'm setting the parameter well (id). Thank you.
PS: I have deleted parts of the code and only left the most important, if you need the full code I can provide it
You're losing the reference to this because you're using an old-style lambda.
Replace this
data.map(function(jsonData) {
with an arrow function, like this
data.map(jsonData => {

state property undefined in render function

In the render function on one of my views I am trying to have the opacity of a view be tied to a state property: this.state.infoOpacity.
This is turning an error "undefined is not an object (evaluating 'this.state.infoOpacity')"
Any guidance would be helpful.
export default class BookView extends Component
{
constructor(props) {
super(props);
this.state = {
hideInfo:false,
infoOpacity:0.80,
swiperWidth:Dimensions.get('window').width,
swiperHeight:Dimensions.get('window').height
};
}
render() {
pages.forEach(function(ranPage){
photoViews.push(
<View key={ranPage.letter} style={{width: Dimensions.get('window').width, height: Dimensions.get('window').height}}>
<View style={[styles.meow,{opacity: this.state.infoOpacity}]}>
<Text style={styles.text}>{ranPage.name}</Text>
<Text style={styles.text}>{ranPage.phonetic}</Text>
<Text style={styles.text2}>{ranPage.description}</Text>
</View>
</View>
)
});
return (
<View style={{flex:1}}>
<Swiper showsButtons={false} style={{backgroundColor:'#000'}} width={this.state.swiperWidth} height={this.state.swiperHeight}>
{photoViews}
</Swiper>
</View>
);
}
}
The context changed in your forEach function. Use an arrow function to fix your issue. So instead of
pages.forEach(function(ranPage){ ... });
write this
pages.forEach((ranPage) => { ... });

React Native onpress not working

onRadioPressed does not seem to be called - what am I doing wrong? I also need to get the text contained in the 'clicked' item.
I believe I can get that with event.nativeEvent.text, correct?
Thanks for any help.
class RadioBtn extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
onRadioPressed(event) {
console.log('RADIOBUTTON PUSHED:');
}
render() {
return (
<View style={styles.radioGrp}>
<View style={styles.radioContainer}>
<TouchableHighlight onpress={() => this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
<Text style={styles.radio}>Left</Text>
</TouchableHighlight>
</View>
<View style={styles.radioContainer}>
<TouchableHighlight onpress={() => this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
<Text style={styles.radio}>Right</Text>
</TouchableHighlight>
</View>
</View>
);
}
}
So here:
<TouchableHighlight onpress={() => this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
<Text style={styles.radio}>Left</Text>
</TouchableHighlight>
First change onpress to onPress. Here () => this.onRadioPressed.bind(this) you are specifying an arrow function that returns another function this.onRadioPressed.bind(this) but you never trigger it.
Correct ways:
// You can do either this
<TouchableHighlight onPress={() => this.onRadioPressed()} underlayColor='#f1c40f'>
<Text style={styles.radio}>Left</Text>
</TouchableHighlight>
// Or you can do either this
<TouchableHighlight onPress={this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
<Text style={styles.radio}>Left</Text>
</TouchableHighlight>
I would recommend checking this article out https://medium.com/#housecor/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56#.irpdw9lh0
You can not bind the function inside onpress link this :
<TouchableHighlight onpress={() => this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
use it like this :
<TouchableHighlight onpress={() => this.onRadioPressed()} underlayColor='#f1c40f'>
if you want to bind the function then try this:
<TouchableHighlight onpress={this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
Cheers:)
Use below line
<TouchableHighlight onPress={this.onRadioPressed.bind(this)} underlayColor='#f1c40f'>
or using arrow function
<TouchableHighlight onPress={() => this.onRadioPressed()} underlayColor='#f1c40f'>
if https://stackoverflow.com/a/41651845/9264008 doesn't works check the way you have imported TouchableOpacity
✅ correct import import { TouchableOpacity } from 'react-native'
sometimes mistakenly weird import happens example below
❌ Import import { TouchableOpacity } from 'react-native-gesture-handler'
I'm using react-native 0.66 version and it's working fine.
import React, { useState } from 'react';
import { StyleSheet,Text,View } from "react-native";
const App = () => {
const [ prevCount, setCount ] = useState(1)
const onPress = () => setCount(prevCount => prevCount + 1);
return (
<View style={styles.container}>
<Text style={styles.prevCount}> {prevCount} </Text>
<Text style={styles.pressHere} onPress={onPress} > Press Here </Text>
</View>
)
};
const styles = StyleSheet.create({
container: {
marginTop: 50
},
pressHere:{
fontSize: 30
},
prevCount: {
fontSize: 20,
color: 'red'
}
})
export default App;
also, you can use this doc.