React native useState and return statement not working together - javascript

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

Related

react native TouchableOpacity, different functions by first and second click

I'm creating a simple text-to-speech function for my react native app.
I have a button, when you click it for the first time, it will read the text and play the sound.
But I want to make it dynamic. For example: If you click again it should stop, if click again, should play again, etc.....
But now, it is only available for playing the sound with any click.
Where/how should I execute the stopReadText()?
I still don't have any idea about this. Thanks a lot.
Here is the code:
const readText = () => {
Speech.speak('text')
}
const stopReadText = () => {
Speech.stop()
}
return (
<View>
<TouchableOpacity onPress=(readText)>
<Divider style={styles.modalDivider} />
<Image
style={styles.speaker}
source={require('../../assets/speaker.png')}
/>
</TouchableOpacity>
</View>
)
(I am using expo-speech)
You can do it by taking on a boolean state variable:
import { useState } from 'react';
const [isPlay,setIsPlay]=useState(false)
const readText = () => {
Speech.speak('text')
}
const stopReadText = () => {
Speech.stop()
}
const handlePlay =() =>{
if(!setIsPlay){
readText()
setIsPlay(true)
}
else {
stopReadText()
setIsPlay(false)
}
}
return (
<View>
<TouchableOpacity onPress={handlePlay}>
<Divider style={styles.modalDivider} />
<Image
style={styles.speaker}
source={require('../../assets/speaker.png')}
/>
</TouchableOpacity>
</View>
)

React Native: Passing useState() data to unrelated screens

Explanation: I am creating a fitness app, my fitness app has a component called WorkoutTimer that connects to the workout screen, and that screen is accessed via the HomeScreen. Inside the WorkoutTimer, I have an exerciseCount useState() that counts every time the timer does a complete loop (onto the next exercise). I have a different screen called StatsScreen which is accessed via the HomeScreen tab that I plan to display (and save) the number of exercises completed.
What I've done: I have quite literally spent all day researching around this, but it seems a bit harder with unrelated screens. I saw I might have to use useContext() but it seemed super difficult. I am fairly new to react native so I am trying my best haha! I have attached the code for each screen I think is needed, and attached a screenshot of my homeScreen tab so you can get a feel of how my application works.
WorkoutTimer.js
import React, { useState, useEffect, useRef } from "react";
import {
StyleSheet,
Text,
View,
TouchableOpacity,
Button,
Animated,
Image,
SafeAreaView,
} from "react-native";
import { CountdownCircleTimer } from "react-native-countdown-circle-timer";
import { Colors } from "../colors/Colors";
export default function WorkoutTimer() {
const [count, setCount] = useState(1);
const [exerciseCount, setExerciseCount] = useState(0);
const [workoutCount, setWorkoutCount] = useState(0);
const exercise = new Array(21);
exercise[1] = require("../assets/FR1.png");
exercise[2] = require("../assets/FR2.png");
exercise[3] = require("../assets/FR3.png");
exercise[4] = require("../assets/FR4.png");
exercise[5] = require("../assets/FR5.png");
exercise[6] = require("../assets/FR6.png");
exercise[7] = require("../assets/FR7.png");
exercise[8] = require("../assets/FR8.png");
exercise[9] = require("../assets/S1.png");
exercise[10] = require("../assets/S2.png");
exercise[11] = require("../assets/S3.png");
exercise[12] = require("../assets/S4.png");
exercise[13] = require("../assets/S5.png");
exercise[14] = require("../assets/S6.png");
exercise[15] = require("../assets/S7.png");
exercise[16] = require("../assets/S8.png");
exercise[17] = require("../assets/S9.png");
exercise[18] = require("../assets/S10.png");
exercise[19] = require("../assets/S11.png");
exercise[20] = require("../assets/S12.png");
exercise[21] = require("../assets/S13.png");
return (
<View style={styles.container}>
<View style={styles.timerCont}>
<CountdownCircleTimer
isPlaying
duration={45}
size={240}
colors={"#7B4FFF"}
onComplete={() => {
setCount((prevState) => prevState + 1);
setExerciseCount((prevState) => prevState + 1);
if (count == 21) {
return [false, 0];
}
return [(true, 1000)]; // repeat animation for one second
}}
>
{({ remainingTime, animatedColor }) => (
<View>
<Image
source={exercise[count]}
style={{
width: 150,
height: 150,
}}
/>
<View style={styles.timeOutside}>
<Animated.Text
style={{
color: animatedColor,
fontSize: 18,
position: "absolute",
marginTop: 67,
marginLeft: 35,
}}
>
{remainingTime}
</Animated.Text>
<Text style={styles.value}>seconds</Text>
</View>
</View>
)}
</CountdownCircleTimer>
</View>
</View>
);
}
const styles = StyleSheet.create({})
WorkoutScreen.js
import React, { useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import WorkoutTimer from "../components/WorkoutTimer";
export default function WorkoutScreen() {
return (
<View style={styles.container}>
<WorkoutTimer />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
HomeScreen.js
import React from "react";
import { StyleSheet, Text, View, SafeAreaView, Button } from "react-native";
import { TouchableOpacity } from "react-native-gesture-handler";
import { AntDesign } from "#expo/vector-icons";
import { Colors } from "../colors/Colors";
export default function HomeScreen({ navigation }) {
return (
<SafeAreaView style={styles.container}>
<Text style={styles.pageRef}>SUMMARY</Text>
<Text style={styles.heading}>STRETCH & ROLL</Text>
<View style={styles.content}>
<TouchableOpacity
style={styles.timerDefault}
onPress={() => navigation.navigate("WorkoutScreen")}
>
<Button title="START WORKOUT" color={Colors.primary} />
</TouchableOpacity>
<TouchableOpacity
style={styles.statContainer}
onPress={() => navigation.navigate("StatsScreen")}
>
<AntDesign name="barschart" size={18} color={Colors.primary} />
<Text style={{ color: Colors.primary }}>Statistics</Text>
<AntDesign name="book" size={18} color={Colors.primary} />
</TouchableOpacity>
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({})
StatsScreen.js
import React from "react";
import { StyleSheet, Text, View } from "react-native";
import { exerciseCount, workoutCount } from "../components/WorkoutTimer";
export default function StatsScreen() {
return (
<View style={styles.container}>
<Text display={exerciseCount} style={styles.exerciseText}>
{exerciseCount}
</Text>
<Text display={workoutCount} style={styles.workoutText}>
{workoutCount}
</Text>
</View>
);
}
const styles = StyleSheet.create({});
Home Screen Image
As far as I can tell, you're almost there! You're trying to get your 2 state
variables from the WorkoutTimer like this:
import { exerciseCount, workoutCount } from "../components/WorkoutTimer";
Unfortunatly this won't work :( . These two variables change throughout your
App's life-time and that kinda makes them "special".
In React, these kinds of variables need to be declared in a parent component
and passed along to all children, which are interested in them.
So in your current Setup you have a parent child relationship like:
HomeScreen -> WorkoutScreen -> WorkoutTimer.
If you move the variables to HomeScreen (HomeScreen.js)
export default function HomeScreen({ navigation }) {
const [exerciseCount, setExerciseCount] = useState(0);
const [workoutCount, setWorkoutCount] = useState(0);
you can then pass them along to WorkoutScreen or StatsScreen with something
like:
navigation.navigate("WorkoutScreen", { exerciseCount })
navigation.navigate("StatsScreen", { exerciseCount })
You'll probably have to read up on react-navigation's documentation for .navigate I'm not sure I remember this correctly.
In order to read the variable you can then:
export default function WorkoutScreen({ navigation }) {
const exerciseCount = navigation.getParam(exerciseCount);
return (
<View style={styles.container}>
<WorkoutTimer exerciseCount={exerciseCount} />
</View>
);
}
and finally show it in the WorkoutTimer:
export default function WorkoutTimer({ exerciseCount }) {
Of course that's just part of the solution, since you'll also have to pass
along a way to update your variables (setExerciseCount and setWorkoutCount).
I encourage you to read through the links I posted and try to get this to work.
After you've accumulated a few of these stateful variables, you might also want to look at Redux, but this is a bit much for now.
Your app looks cool, keep at it!
I ended up solving this problem with useContext if anyone is curious, it was hard to solve initially. But once I got my head around it, it wasn't too difficult to understand.
I created another file called exerciseContext with this code:
import React, { useState, createContext } from "react";
const ExerciseContext = createContext([{}, () => {}]);
const ExerciseProvider = (props) => {
const [state, setState] = useState(0);
//{ exerciseCount: 0, workoutCount: 0 }
return (
<ExerciseContext.Provider value={[state, setState]}>
{props.children}
</ExerciseContext.Provider>
);
};
export { ExerciseContext, ExerciseProvider };
and in App.js I used ExerciseProvider which allowed me to pass the data over the screens.
if (fontsLoaded) {
return (
<ExerciseProvider>
<NavigationContainer>
<MyTabs />
</NavigationContainer>
</ExerciseProvider>
);
} else {
return (
<AppLoading startAsync={getFonts} onFinish={() => setFontsLoaded(true)} />
);
}
}
I could call it with:
import { ExerciseContext } from "../components/ExerciseContext";
and
const [exerciseCount, setExerciseCount] = useContext(ExerciseContext);
This meant I could change the state too! Boom, solved! If anyone needs an explanation, let me know!
I think you have to use Mobx or Redux for state management. That will be more productive for you instead built-in state.

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

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 }

How to use custom alert in React Native?

I've created a custom alert as a component in React Native. I used Modal to create this custom alert. My problem is, how to use it? Instead of using Alert.alert in React Native, I want to display my own alert.
Here is my Custom Alert Modal.
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import Modal from 'react-native-modal';
import styles from './style';
import Button from '../../components/Button';
export default class CustomAlert extends Component {
renderModalContent = () => (
<View style={styles.content}>
<Text style={styles.contentTitle}>{this.props.title}</Text>
<Text style={styles.contentInfo}>{this.props.content}</Text>
<View style={styles.buttonContainer}>
<Button
color={this.props.buttonColor}
text={this.props.buttonText}
onPress={this.props.buttonOnPress}
/>
</View>
</View>
);
render() {
return (
<View style={styles.container}>
<Modal
isVisible={this.props.isVisible}
backdropColor="#000000"
backdropOpacity={0.9}
animationIn="zoomInDown"
animationOut="zoomOutUp"
animationInTiming={600}
animationOutTiming={600}
backdropTransitionInTiming={600}
backdropTransitionOutTiming={600}
>
{this.renderModalContent()}
</Modal>
</View>
);
}
}
This is how I want to use it. I want to display this alert through a function. That means when function catches up with an error, I want to show my custom alert.
myFunction()
.then(() => // do something)
.catch(() => // show my custom alert);
Can you help me please to solve this problem?
set isVisible true in your catch block.
myFunction()
.then(() => // do something)
.catch((e) => this.setState({ isVisible: true }))

How to connect react component in react navigation?

I have created modal in react native. I have added filter option icon in top right corner now when the user clicks on it should open the modal. How can I do that ? I have added Options icon in navigation.js but now how to connect it with modal component ?
In code below setModalVisible is available in filteroptions.js and not in navigation.js
Code:
navigation.js:
Updates: {
screen: UpdatesScreen,
navigationOptions: ({ navigation }) => ({
headerTitle: 'Myapp',
headerRight:<TouchableOpacity onPress={() => {this.setModalVisible(true);}}>
<MenuIcon style={{paddingLeft: 10, paddingRight: 15}} name="md-options" size={25} color="white"/>
</TouchableOpacity>,
})
},
filteroptions.js:
import React, {Component} from 'react';
import {Modal, Text, TouchableHighlight, View, Alert} from 'react-native';
export default class FilteroptionsModel extends Component {
state = {
modalVisible: false,
};
setModalVisible(visible) {
this.setState({modalVisible: visible});
}
render() {
return (
<View style={{marginTop: 22}}>
<Modal
animationType="slide"
transparent={false}
visible={this.state.modalVisible}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View style={{marginTop: 22}}>
<View>
<TouchableHighlight
onPress={() => {
this.setModalVisible(!this.state.modalVisible);
}}>
<Text>Hide Modal</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
</View>
);
}
}
When user clicks on filter button in top right corner (see screenshot) he should be able to see the box modal on screen:
Since it is a modal you don't necessarily need to add it to the navigation. You can just include it in your page and initially have it be invisible, then when the user clicks your button you can make the modal visible. But if you want to add it to the navigation why not just add like any other component. However, adding it to the navigation will take you to another page when you navigate to the component. Of course you can add a nested navigator to work around that, but I think it adds unnecessary complexity.
Update
You will first declare a Header component.
export default class MyHeader extends React.PureComponent {
render() {
<View>
<View>...Your left Icon here</View>
<View>...Your Title here</View>
<View>...Your right Icon Here</View>
</View>
}
}
Then in your page you will render this component first, pass as props your handlers and then render the rest of the page.
export default class MyPage extends React.PureComponent {
yourRigthHandler = () => {
this.setState({modaVisible: true});
}
yourLeftHandler = () => {....}
render() {
<View>
<MyHeader
LeftHandler={yourLeftHandler}
LeftHandler={yourRigthHandler}>
....
</MyHeader>
</View>
}
}
inside the handlers you can call the navigation functions to navigate to another page or change the components state to make the moda visible.The handlers will be passed as props to your header and you will add them as onPress handlers to your buttons.

Categories