How to use TouchableOpacity to hide view by in React Native? - react-native

I'm really new to React Native and I'm wondering how can I hide/show View
Here's my test code:
class Counter extends React.Component{
state = { count:0 };
setCount = () => this.setState(
prevState => ({ ...prevState, count: this.state.count + 1 })
)
render(){
const { count } = this.state;
const [valueLocation, onChangeText] = React.useState('Pleas input Address');
const [value, onChangeEvent] = React.useState('Your questions');
return (
<ScrollView style={styles.header}>
<View style={styles.box1}>
<View style={styles.box2}>
<View style={styles.user}>
<Image
style={styles.userImg}
source={{
uri: event.user[0].image,
}}
/>
<View style={styles.userText}>
<Text style={styles.username}>{event.user[0].name}</Text>
<Text style={styles.date}>{event.user[0].date}</Text>
</View>
</View>
<View style={styles.boxHidebtn}>
<View style={styles.EventClass}>
<Text style={styles.btn_text_white}>類型</Text>
</View>
<TouchableOpacity
style={styles.EventOpen}
onPress={this.setCount}
>
<Text>></Text>
</TouchableOpacity>
</View>
</View>
<View style={count % 2 ? styles.box3 : styles.box3Open}>
<Text style={styles.address}>台北市市民大道六段37號</Text>
<Text style={styles.eventShow}>路上坑洞造成積水</Text>
</View>
</View>
</ScrollView>
);
}
}
const App = () => {
<Counter/>
};
const styles = StyleSheet.create({
....
});
export default App;
I run my code and it tell me
"App(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
thanks!!!!!!!!

It looks like your arrow function needs to return the Counter:
const App = () => {
return <Counter/>;
};
Or, simply:
const App = () => <Counter/>;

I can see three errors in your code:
const App = () => {
return <Counter/>; // here you should return Counter
};
prevState -> this.state I guess
setCount = () => this.setState({ ...this.state, count: this.state.count + 1 }); // here
you have also a syntax error <Text>></Text> remove this extra closing > inside touchableopacity
Regarding your question in the title? I can't see where you want to hide the view?

Related

Why my virtualized list does not re-render when the data passed as prop actualizes?

I am having a problem that I can't solve by my own. I am making an app for making lists in React Native, and in my main screen, that shows the session initiated by the user, I have to render all the lists that he had saved previously. Here is the code of my session component.
export default function Session({navigation,route}){
const {user} = useContext(myContext)
const [modalVisible, setModalVisible] = useState(false)
const [lists, setLists] = useState(route.params.lists)
let keyListCounter = 0
const handleButton = async () => {
await AsyncStorage.removeItem("token")
navigation.navigate("Login")
}
const updateList = (title,newElement) => {
axios.put(`http://${REACT_APP_BACK_URI}/api/lists/add-list-element`, {nickname: user,title,element: newElement})
.then(res => {
if (res.status == 200) {
setLists(res.data.userLists)
}
})
.catch(err => console.log(err))
}
useEffect(() => {
navigation.setOptions({
title: user,
headerTitleAlign: "left",
headerRight: () => (
<TouchableWithoutFeedback onPress={() => handleButton()}>
<Text style={styles.logoutText}>Logout</Text>
</TouchableWithoutFeedback>
)
})
},[navigation,user])
return (
<View style={styles.mainContainerView}>
<ScrollView style={styles.mainContainerScrollView}>
<View style={styles.textListContainer}>
<Text style={styles.listsText}>LISTAS ACTIVAS: </Text>
<Text style={styles.numberListsText}>{lists.length}</Text>
</View>
{lists.map(elem => <List key={keyListCounter++} list={elem} updateList={updateList}/>)}
</ScrollView>
<Pressable style={styles.newListPressable} onPressIn={() => setModalVisible(true)}>
<Text style={styles.newListText}>+</Text>
</Pressable>
<View style={styles.centeredView}>
<Modal
visible={modalVisible}
animationType="slide"
transparent={true}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text>MODAL</Text>
</View>
</View>
</Modal>
</View>
</View>
)
}
My question is why after I actualize the state of "lists", whose elements are passed as props to the List component, the virtualized list that I have in the List component does not re-renderizes automaticaly.
Here I show also the code of the List component.
export default function List({list,updateList}){
const {elements, title} = list
let elementId = 0
const virtualizedList = useRef()
const [showVirtualizedList, setShowVirtualizedList] = useState("none")
const [showDownArrow, setShowDownArrow] = useState(true)
const [showUpArrow, setShowUpArrow] = useState(false)
let [newElementArray, setNewElementArray] = useState([])
let [listElements, setListElements] = useState(elements)
const getItem = (item) => ({
id: elementId++,
title: item
});
//List Pressable Events
const handlePressIn = () => {
if (showVirtualizedList == "none") setShowVirtualizedList("flex")
else setShowVirtualizedList("none")
setShowDownArrow(!showDownArrow)
setShowUpArrow(!showUpArrow)
}
//New element Pressable Events
const handleNewElement = () => {
setNewElementArray([...newElementArray,uuid.v4()])
}
//NewListItem TouchableWithoutFeedback Events
const deleteElementInput = newItemID => {
const elementsArray = newElementArray.filter(elem => elem != newItemID)
setNewElementArray(elementsArray)
}
const addListElement = (newElement,newItemID) => {
updateList(title,newElement)
deleteElementInput(newItemID)
}
useEffect(() => {
virtualizedList.current.setNativeProps({display: showVirtualizedList})
LogBox.ignoreLogs(['VirtualizedLists should never be nested']);
},[showVirtualizedList, virtualizedList])
return (
<ScrollView style={styles.mainContainer}>
<Pressable
style={styles.listElement}
onPressIn={() => handlePressIn()}
>
<View style={styles.titleContainer}>
<Text style={styles.listElementText}>{title} </Text>
<Text style={styles.listElementQuantity}>({listElements.length})</Text>
</View>
<View>
<DownArrow show={showDownArrow}/>
<UpArrow show={showUpArrow}/>
</View>
</Pressable>
<View>
<VirtualizedList
data={listElements}
initialNumToRender={10}
getItemCount={() => listElements.length}
renderItem={({item}) => <ListItem item={item}/>}
getItem={() => getItem(listElements[elementId])}
ref={virtualizedList}
/>
</View>
{newElementArray.length > 0 ? newElementArray.map(elem => {
return (
<NewListItem
key={elem}
id={elem}
newElementArray={newElementArray}
deleteElementInput={deleteElementInput}
addListElement={addListElement}
/>
)
}) : ""
}
<Pressable style={styles.newElementPressable} onPressIn={() => handleNewElement()}>
<Text style={styles.newElementText}>+</Text>
</Pressable>
</ScrollView>
)
}
UPDATE: I solve the problem using a FlatList instead of a VirtualizedList. For some reason the FlatList re-renders when the Item is updated and the VirtualizedList no. I don't know why.....

fetch API call in react native is not working when I load the screeen

I have made an App in react native. My app makes API calls to my webserver and then Displays information based on that. The problem Is when I first load this screen... I get the loading screen and the information is display in the way it is supposed to but when I leave the screen and then comeback to the screen, it shows nothing and my array containing the items is empty, hence I think I am having problems with the API call when I leave the screen and then come back.
I am using React navigation 5 in My App.
export default function ({ navigation }) {
const [openQueries, setOpenQueries] = useState([]);
const [isLoading, seIsLoading] = useState(true);
const open_queries = [];
function getOpenQueries() {
var retrieveData = async () => {
try {
var value = await AsyncStorage.getItem("user");
var data = JSON.parse(value);
return data.user._id;
} catch (error) {
alert(error);
}
};
retrieveData().then((user) => {
fetch(URL + "/api/contact/open_queries", {
method: "POST",
body: "user=" + user + "&status=open",
headers: { "Content-type": "application/x-www-form-urlencoded" },
})
.then((response) => {
return response.json();
})
.then((responseJson) => {
if (responseJson.error === null) {
setOpenQueries(responseJson.open_queries);
seIsLoading(false);
}
});
});
}
getOpenQueries();
openQueries.forEach((query) => {
open_queries.push(
<TouchableOpacity
onPress={() =>
navigation.navigate("Chat", {
id: query._id,
title: query.title,
query: query,
showInput: true,
})
}
>
<View style={styles.inboxItem}>
<Text style={styles.inboxTitle}>{query.title}</Text>
<Text style={styles.inboxSubtext}>
{query.chats[query.chats.length - 1].chat}
</Text>
<View style={styles.lineBreak}></View>
</View>
</TouchableOpacity>
);
});
return (
<SafeAreaView style={styles.container}>
<Text style={styles.title}>Contacts</Text>
<TouchableOpacity
style={styles.button}
onPress={() => navigation.navigate("NewQuery")}
>
<Text style={styles.text}>Start a new query</Text>
</TouchableOpacity>
<TouchableOpacity onPress={() => navigation.navigate("ClosedQueries")}>
<View style={styles.button}>
<Text style={styles.text}>Closed Queries</Text>
</View>
</TouchableOpacity>
<Text style={styles.subTitle}>Open Queries</Text>
{isLoading ? (
<View style={styles.loader}>
<Code />
</View>
) : (
<ScrollView style={{ paddingTop: 10 }}>
{openQueries.length > 0 ? (
open_queries
) : (
<Text style={styles.noQuery}>No Open Queries found</Text>
)}
</ScrollView>
)}
<ScrollView></ScrollView>
<BottomNavigation navigation={navigation} active={"contact"} />
</SafeAreaView>
);
}
Try this way
export default function ({ navigation }) {
const [openQueries, setOpenQueries] = useState([]);
const [isLoading, seIsLoading] = useState(true);
const [open_queries_views, setOpenQueriesViews] = useState([]);
function getOpenQueries() {
....
}
// Similar to componentDidMount
useEffect(() => {
getOpenQueries();
});
function renderViews(){
const open_queries = [];
openQueries.forEach((query) => {
open_queries.push(
<TouchableOpacity> ... </TouchableOpacity>
);
});
setOpenQueriesViews(open_queries); // set state here to auto reflect on view
}
return (
<SafeAreaView style={styles.container}>
....
<ScrollView style={{ paddingTop: 10 }}>
{open_queries_views.length > 0 ? (
open_queries_views
) : (
<Text style={styles.noQuery}>No Open Queries found</Text>
)}
</ScrollView>
.....
</SafeAreaView>
);
}

How to access one functional component's state from another functional component in react-native?

I want to access ModalView's state from MarkerView component. Actually i want to see ModalView when i click Get info. button which is in MarkerView. I want to set { setVisiblity(true)} from MarkerView component. How can i do it?
ModalView.js
const ModalView = () => {
const [visiblity, setVisiblity] = useState(false);
return (
<Modal transparent={false} visible={visiblity} >
<TouchableOpacity onPress={() => { setVisiblity(false)}}>
<Text> Submit </Text>
</TouchableOpacity>
</Modal>
)
}
MarkerView.js
const MarkerView = () => {
return (
// i want to set visiblity true from here
<View>
<TouchableOpacity onPress={() => { setVisiblity(true) }}>
<Text>Get info.</Text>
</TouchableOpacity>
</View>
)
}
App.js
import ModalVIew from './components/ModalView';
import Marker from './components/MarkerView';
const App = () => {
return (
<View>
<Marker/>
<ModalVIew/>
</View>
)
}
export default App;
you can use state management like contextAPI or redux, or you can put your state on your higher order component but this will result in some prop drilling.
App.js
const App = () => {
const [visiblity, setVisiblity] = useState(false);
return (
<View>
<Marker visiblity={visiblity} onChangeVisiblity={(val) => setVisiblity(val)}/>
<ModalVIew visiblity={visiblity} onChangeVisiblity={(val) => setVisiblity(val)}/>
</View>
)
}
MarkerView.js
const MarkerView = ({visiblity, onChangeVisiblity: changeVisiblity}) => {
return (
<View>
<TouchableOpacity onPress={() => changeVisiblity(true)}>
<Text>Get info.</Text>
</TouchableOpacity>
</View>
)
}
ModalView.js
const ModalView = ({visiblity, onChangeVisiblity:changeVisiblity}) => {
const [visiblity, setVisiblity] = useState(false);
return (
<Modal transparent={false} visible={visiblity} >
<TouchableOpacity onPress={() => changeVisiblity(false)}>
<Text> Submit </Text>
</TouchableOpacity>
</Modal>
)
}

Implement onPress on Flatlist item

I am trying to send the data of the flatlist items when clicked and set to another class.The ontouch is working but I am having the error below in the image. Also how can I send the data of api to the other class and get from another class? I have implemented as follows:
export default class FlatSpeakers extends Component {
constructor(props) {
super(props);
this.state = { isLoading: true, data: [],selectedItem: null, }
const { navigate } = this.props.navigation;
}
onPressItem = () => {
navigate('SpeakersClick')
};
componentDidMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(res => {
this.setState({
isLoading: false,
data: res.data,
})
})
}
renderItem({ item }) {
return (
<TouchableOpacity onPress={()=>this.onPressItem(item)} >
<Card>
<CardSection>
<View style={styles.thumbnailContainerStyle}>
<Image
style={styles.thumbnailStyle}
source={{ uri: item.image }}
/>
</View>
<View style={styles.headerContentStyle}>
<Text style={styles.headerTextStyle}>{item.title}</Text>
<Text>{item.artist}</Text>
</View>
</CardSection>
</Card>
</TouchableOpacity>
)
}
render() {
if (this.state.isLoading) {
return (
<View style={{ flex: 1, padding: 20 }}>
<ActivityIndicator />
</View>
)
}
return (
<View style={styles.container}>
<FlatList
data={this.state.data}
renderItem={this.renderItem}
keyExtractor={(item, index) => index}
onPress={this.onPressItem}
/>
</View>
);
}
}
Problem in your code is, that you are calling same method from two sides - on one side you are passing arguments in it on another side you are not passing arguments. If you wan't to have both cases covered you should change you onPressFunction, to accept arguments - in your case item:
onPressItem = (item) => {
navigate('SpeakersClick')
};
try to put this.onPressItem = this.onPressItem.bind(this) on constructor(props)

Loading Indicator while loading item

I am making react native expo app. And i have page where articles from database are displayed. When i click to button of article i go to page with article. When i click button i am sending all data of article to another screen. I want to load ActivityIndicator while data is displaying.
Help me please
Code:
class HomeScreen extends React.Component {
const { navigate } = this.props.navigation;
return (
<SafeAreaView style={styles.MainContainer}>
<ScrollView
>
<ListView
dataSource={this.state.dataSource}
renderSeparator={this.ListViewItemSeparator}
renderRow={rowData => (
<>
<TouchableOpacity style={{flex:2}}
activeOpacity={.7}
onPress={() => navigate('Articles', {
otherParam: rowData.article_title,
mobile_image: rowData.mobile_image,
article_category: rowData.article_category,
views: rowData.views,
article_content: rowData.article_content
})}>
<Image
source = {{ uri: rowData.mobile_image }}
style={{resizeMode:'cover',width:null,height:null, flex:1, borderRadius:4,
borderWidth:1,
borderColor:'#dddddd'}}
/>
<Text
style={styles.textOfArticle}
>
{rowData.article_title}
</Text>
</TouchableOpacity>
</>
)}
/>
</ScrollView
>
</SafeAreaView>
);
}
}
class ArticleScreen extends React.Component {
static navigationOptions = ({ navigation, navigationOptions }) => {
const { params } = navigation.state;
return {
title: params ? params.otherParam : '',
};
};
state = { animating: true }
componentDidMount = () => {
const { params } = this.props.navigation.state;
const article_title = params ? params.otherParam : '';
const mobile_image = params ? params.mobile_image : '';
const article_category = params ? params.article_category : '';
const views = params ? params.views : '';
const article_content = params ? params.article_content : '';
this.closeActivityIndicator()
}
render() {
const animating = this.state.animating
return (
<View style = {styles.container}>
<ActivityIndicator
animating = {animating}
color = '#bc2b78'
size = "large"
style = {styles.activityIndicator}/>
</View>
)
return (
<SafeAreaView>
<ScrollView>
<Text>{article_title}</Text>
</ScrollView>
</SafeAreaView>
);
}
}
Add a boolean value for activityIndicator, which will used to show or hide activityIndicator.
state = {
showIndicator: true,
}
closeActivityIndicator = () => {
this.setState({ showIndicator: false });
}
In your render use conditional rendering based on showIndicator value
render() {
const animating = this.state.animating;
return (
<SafeAreaView>
{this.state.showIndicator ? (
<View style={styles.container}>
<ActivityIndicator
animating={animating}
color="#bc2b78"
size="large"
style={styles.activityIndicator}
/>
</View>
) : (
<ScrollView>
<Text>{article_title}</Text>
</ScrollView>
)}
</SafeAreaView>
);
}