Adjacent JSX elements must be wrapped in an enclosing tag React Native - javascript

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 }

Related

Error in putting ImageView component within View component

When I'm putting ImageView component within View component, I am getting the error: Error: Text strings must be rendered within a component. I don't understand what is wrong over here. Below is the code snippet:
import React from 'react';
import { View, Image, ScrollView, TouchableOpacity, Modal, Text } from 'react-native';
import styles from './cameraStyles';
import ImageView from "react-native-image-viewing";
export default ({captures=[], lflagImage=false}) => {
const [flagImage, setflagImage] = React.useState(lflagImage);
return (
<ScrollView horizontal={true} style={[styles.bottomToolbar, styles.galleryContainer]}>
{captures.map(({ uri }) => (
<View style={styles.galleryImageContainer} key={uri}>
<TouchableOpacity onPress={()=> {setflagImage(prevData => !prevData)}}>
<Image source={{ uri }} style={styles.galleryImage}/>
</TouchableOpacity>
<ImageView
images={captures}
imageIndex={0}
visible={flagImage}
onRequestClose={() => setflagImage(prevData => !prevData)}
/>
</View>
))}
</ScrollView>
)
}
It looks like you have an extra set of braces within your TouchableOpacity's onPress event. It should be:
onPress={()=> setflagImage(prevData => !prevData)}
This could be causing the issue you are experiencing.
I also can't see what styles.galleryImage is, but make sure you are defining a height and width or else it won't display anyway.

Why doesn't react native register the user pressing a button?

I'm trying to use a touchablehighlight component and when I press it, nothing happens. So I changed it to a button and added a console log and still, react native won't register the press.
I'm using expo and I'm relatively new to react native.
Please tell me what I'm doing wrong
import React, { useState } from "react";
import {
Button,
Modal,
StyleSheet,
Text,
TouchableHighlight,
View,
} from "react-native";
const customPicker = (props) => {
const [selectedNumber, setSelectedNumber] = useState(props.pickerValues[0]);
const [pickerDisplayed, setPickerDisplayed] = useState(false);
function changeSelectedNumber(value) {
setSelectedNumber(value);
setPickerDisplayed(false);
}
const touchableHighlightcomponent = props.pickerValues.map((value, index) => (
<TouchableHighlight
style={styles.th}
onPress={() => changeSelectedNumber({ value })}
key={index}
>
<Text>{value}</Text>
</TouchableHighlight>
));
return (
<View>
<Button onPress={() => console.log("pressed")} title="one"></Button>
{/* <TouchableHighlight style={styles.input} onPress={() => this.console.log("pressed")}>
<Text>{selectedNumber}</Text>
</TouchableHighlight> */}
<Modal visible={() => pickerDisplayed} transparent={true}>
<View style={styles.picker}>
<View style={styles.pickerItems}>
<Text>Please select a value</Text>
{touchableHighlightcomponent}
</View>
</View>
</Modal>
</View>
);
};
I have discovered the problem.
It's a bug with the iOS simulator, it doesn't register button pushes.
To fix: Simply restart the iOS simulator

React native useState and return statement not working together

Here whenever i click the icon it doesnt show anything. It supposed to be showing some text and when clicked again it should hide the text. Im using react native.
import React, { useState } from 'react';
import { View, Text, StyleSheet, Button, Image, TouchableOpacity} from 'react-native';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
export default function Edit(props, { navigation }) {
const [slide, setSlide] = useState(false);
const toggle = () => {
setSlide(!slide);
console.log('clicked');
return (
<View>
<Text>random</Text>
<Text>random</Text>
</View>
);
}
return (
<View>
<FontAwesome name="sliders" size={30} color="#000" onPress={() => toggle()}/>
</View>
}
After testing the only thing it shows is the console.log('clicked') message. It does not display anything else. Also the icon displays normally. Everything is working except the and the content in those tags.
Rather than returning the View from your toggle function, you actually need to display that view your view hierarchy (eg what is returned from your component).
I've demonstrated in the example by using a ternary expression -- if slide is true, it gets shown, otherwise it does not.
export default function Edit(props, { navigation }) {
const [slide, setSlide] = useState(false);
const toggle = () => {
setSlide(!slide);
console.log('clicked');
}
return (
<View>
<FontAwesome name="sliders" size={30} color="#000" onPress={() => toggle()}/>
{slide ? <View>
<Text>random</Text>
<Text>random</Text>
</View> : null}
</View>
);
}
Snack example: https://snack.expo.io/7lVezwWs7

RN checkbox as card and multi select

I've to select one or two cards from a list of cards , where on tap of each card / checkbox , that card gets highlighted (and is selected). Each card has checkbox on it, which shows that particular card through which selection is made. You can re-tap on the same checkbox to unselect it.
I'm pretty new to react native and confused how to achieve this functionality. Here's the code for reference.
import React, { Component } from 'react';
import {View, Image, StyleSheet} from 'react-native';
import { Container, Content, ListItem, CheckBox, Text, Body } from 'native-base';
export default class Career extends Component {
topics = ['abc','def', 'ghi', 'jkl']
render() {
const extract = this.topics.map((topic, i) => {
return(
<View style={styles.cardContainer}>
<Image style={{width:50, height:50}} source={require('../../assets/images/idcLogo.png')}/>
<CheckBox checked={false}></CheckBox>
<Text>{topic}</Text>
</View>
)
});
return (
<Container>
<Content>
<View style={styles.mainContainer}>
{extract}
</View>
</Content>
</Container>
);
}
}
const styles = StyleSheet.create({
cardContainer: {
borderRadius:5,
borderColor:"#ccc",
borderWidth:2,
justifyContent:'center',
alignItems:'center',
width:'50%',
margin:5
},
mainContainer:{
justifyContent:'center',
width:'100%',
alignItems:'center',
flex:1
}
})
Please let me know if this you need any other information on this. Thanks in advance
I would change the <View style={styles.cardContainer}></View> into <TouchableOpacity style={styles.cardContainer}> then I'll add a function to monitor the changes of the checked status for the button.
I'll add this function before the render function
handleOnTap = (topic) => {
this.setState(prevState => ({ [topic]: !prevState[topic], });
}
<Checkbox onPress={() => this.handleOnTap(topic)} checked={!!this.state[topic]} />
Don't forget to add a key generating elements via this.topics.map; <TouchableOpacity style={styles.cardContainer} key={topic-${i}}>
Hope that helps

this.setState is not a function when used at onPress

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')}>
...

Categories