How can I press individual option in actionsheet in React Native? - reactjs

I am still new to React Native. I have an actionsheet with two options and a cancel option. I am having trouble understanding how to make each option do something different when pressed.
My code:
import React, { useRef } from "react"
import ActionSheet from 'react-native-actionsheet'
import { View, Text, Pressable } from "react-native";
import Icon from 'react-native-vector-icons/FontAwesome';
const ActionSheet = () => {
let actionSheet = useRef();
let optionArray = ['Orange', 'Cherry', 'Cancel'];
const showActionSheet = () => {
actionSheet.current.show();
}
return (
<View
<Pressable onPress={showActionSheet}>
<View>
<Text>Choose Fruit</Text>
<Icon name="angle-right" size={15}/>
</View>
</Pressable>
<ActionSheet
ref={actionSheet}
options={optionArray}
cancelButtonIndex={2}
onPress={{????}}
/>
</View>
);
};
What I'd like to do is navigate to a different screen when an option is pressed
Would appreciate any help. Thank you in advance!

The onPress function provides an index argument. Thus consider the following code snippet.
const onActionSelect = (index) => {
if (index === 1) {
// first action pressed
} else if (index === 2) {
// second action pressed
}
// and so on
}
<ActionSheet
ref={actionSheet}
options={optionArray}
cancelButtonIndex={2}
onPress={onActionSelect}
/>

Related

Radio Button Reset

I'm using this package Radio Button. It's working fine but I need to reset the selected value, for that I can not find any solution there.
you can change state to render new radio button - https://snack.expo.dev/iiHkFYpLV
import React, { useState } from "react";
import { View, StyleSheet, Button, Alert } from "react-native";
import RadioButtonRN from 'radio-buttons-react-native';
const App = () => {
const [show,setShow] = React.useState(true);
const data = [
{
label: 'data 1'
},
{
label: 'data 2'
}
];
React.useEffect(()=>{
if(!show) setShow(true)
},[show])
const resetHandler = () =>{
setShow(false)
}
return (
<View style={styles.container}>
{show &&
<RadioButtonRN
data={data}
selectedBtn={(e) => console.log(e)}
/>
}
<Button title='reset' onPress={resetHandler} />
</View>
);
}
const styles = StyleSheet.create({
container: {
paddingTop:100,
}
});
export default App;
the package does not have the reset functionality but there is a PR pending for the same feature. Whole package is in a single file only, so what you can do is copy package file to your code and add the feature related code from the PR.
or you can use another package ;)

PanGestureHandler state change interrupt gesture

I am using PanGestureHandler from react-native-gesture-handler, everything is working fine but when the state is changed inside onGestureEvent, the PanGestureHandler stop working and I have to release my finger and touch again to start the gesture. Please check the code below that describe my problem:
import React, {useState} from 'react';
import {View, Text} from 'react-native';
import {PanGestureHandler, State} from 'react-native-gesture-handler';
import FastImage from 'react-native-fast-image';
import styles from '../Styles/HomeStyles.js';
const PanResp = () => {
const [testState, setTestState] = useState('State....');
const gestureEventHandler = ({nativeEvent}) => {
if (nativeEvent.x + nativeEvent.translationX <= 74) {
setTestState('New State');
} else {
console.log('X Position => ', nativeEvent.x);
}
};
const onDragRelease = () => {
console.log('Drag Release');
};
return (
<View>
<PanGestureHandler
onGestureEvent={gestureEventHandler}
onEnded={onDragRelease}>
<FastImage
style={styles.imgIcon}
source={{uri: 'http://i.imgur.com/LwCYmcM.gif'}}
/>
<FastImage
style={styles.imgIcon}
source={{uri: 'http://i.imgur.com/k5jMsaH.gif'}}
/>
</PanGestureHandler>
</View>
);
};
export default PanResp;
Note: The above codes work fine, and when the state update and I release my fingers from touch no DragRelease event is firing, and also the PanGestureHandler not respond to touch any more. I am stuck at this point from past week.

How to use onSubmitEditing in react-native?

I tried to use onKeyPress, but since android doesnt get hard keyboard input, i want to use onSubmitEditing,
I have two TextInputs, what I want to do is that when I press on Enter when i am in textInput for firstName, it should be focused on next textInput
const firstNameRef = useRef(null);
const lastNameRef = useRef(null);
useEffect(()=> {
firstNameRef.current.focus();
}, [])
const firstKeyPress = (e) => {
if(e.key ==="Enter"){
lastNameRef.current.focus();
}
}
input.js
import React from "react";
import { TextInput, View } from "react-native";
const Input = React.forwardRef(({placeholder,onKeyPress},ref) => {
return(
<View>
<TextInput ref={ref} placeholder={placeholder}/>
</View>
)
})
export default Input;
Will I only add blurOnSubmit={false} onSubmitEditing={()=>lastNameRef.current.focus()} on Input component?
Yes, it worked.
I only added blurOnSubmit={false} onSubmitEditing={()=>lastNameRef.current.focus()} for the first TextInput, and called it as props, in input.js as blurOnSubmit={blurOnSubmit} onSubmitEditing={onsubmitEditing}
When i press on Enter while in first TextInput, it goes to other input.

React useSelector not working, what am I doing wrong?

I have a selectors folder with the selector.js file
const isRecipeFavorited = state => recipeId => {
const recipe = state.find(recipe => recipe.id === recipeId)
console.log(`Selector isRecipeFavourtied: ${recipeId}`)
return recipe ? recipe.is_fav : false
}
This is my favicon.js file which calls this useSelector.
import React, {useState, useEffect} from 'react'
import { FontAwesome } from '#expo/vector-icons'
import { View, TouchableOpacity,StyleSheet, Text, Alert } from 'react-native'
import {isRecipeFavorited} from '../selectors/selectors'
import {useSelector} from 'react-redux'
import { favids } from '../reducers/favids'
const FavIcon = ({recipeid, onToggle, isFavourite, text}) => {
const isFavNew = useSelector(isRecipeFavorited(recipeid))
return (
<View>
<TouchableOpacity style={styles.favItem} onPress={() => onToggle(recipeid)}>
<FontAwesome name={isFavNew === true ? 'heart' : 'heart-o'} size={40} color='red' />
<Text> {text}</Text>
</TouchableOpacity>
</View>
)
}
export default FavIcon
I keep getting an error saying my selector is not a function. _selectors.isRecipeFavourited is not a function.
I am trying to retrieve the value of the recipe.is_fav from the state.
I am also using Redux in this project.
I think you need to reverse state and recipeId in your selector function, i.e.:
const isRecipeFavorited = recipeId => state => {...}
This is a valid useSelector:
const thing = useSelector(state => state.thing);
In your case, you're calling a function with another type of argument, which in turn should return a function of the type that useSelector is expecting.
This is solved by drilling down into the favids object.
The selector function has been modified as below.
const recipe = state.favids.find(recipe => recipe.recipeid === recipeId)
return recipe ? recipe.is_fav : false
}```

React Native save change switch with Async Storage

Im new in React Native, I have a problem with Switch, I want to save changes, dark mode and Switch, when I turn off the app and come back my changes should be saved. When I close the app, my switch came back to first position and dark mode does not work. I know that Im doing something wrong, but I did not mobile app and this is my first time and I dont know how to use AsyncStorage in this App to work this. Can somebody help me solve this problem?
import React, { createContext, useState, useEffect } from 'react';
import { AsyncStorage } from 'react-native';
export const DarkModeContext = createContext();
export default function DarkModeContextProvider(props) {
const [switchMode, setSwitchMode] = useState(false);
useEffect(() => {
let switch1 = switchMode;
AsyncStorage.setItem('switch1', JSON.stringify(switch1));
});
const SwitchThis = () => {
setSwitchMode(!switchMode);
};
return (
<DarkModeContext.Provider
value={{
switchMode,
SwitchThis
}}
>
{props.children}
</DarkModeContext.Provider>
);
}
and next component:
import React, { useState, useContext } from 'react';
import { View, ScrollView, TouchableOpacity, Text, AsyncStorage } from 'react-native';
import { List } from 'react-native-paper';
import BackgroundImage from './BackgroundImage';
import Clock from './Clock';
import TabIcon from './TabIcon';
import AddButton from './AddButton';
import { DarkModeContext } from './app-context';
const HomeScreen = () => {
const { switchMode } = useContext(DarkModeContext);
displayData = async () => {
try {
let switch1 = await AsyncStorage.getItem('switch1', function (err, switch1) {
JSON.parse(switch1)
}
)
return switch1
}
catch (error) {
return error
}
}
return (
<View
style={{
flex: 1,
backgroundColor: !switchMode ? 'white' : '#353535'
}}
>
<BackgroundImage fabButton={<AddButton/>}>
<Clock />
</BackgroundImage>
<ScrollView>
<List.Section>
<List.Subheader style={{ color: !switchMode ? 'black' : 'white' }}>
Task List
</List.Subheader>
<TouchableOpacity onPress={displayData}>
<Text>Click displayData</Text>
</TouchableOpacity>
</List.Section>
</ScrollView>
</View>
);
};
You are importing AsyncStorage from 'react-native' which is deprecated
use #react-native-community/react-native-async-storage
npm i #react-native-community/react-native-async-storage
And on your home screen you are not calling the function displayData() so how is data supposed to be displayed without function call.
and i do suggest making separate functions for writing and reading from async storage, it will help you reduce your code and time.
Like this:
let storeData=(name, obj)=> {
return new Promise((resolve,reject)=>{
let jsonOfItem = JSON.stringify(obj)
AsyncStorage.setItem(name, jsonOfItem).then(r=>resolve(jsonOfItem))
.catch(e=>reject(e))
})
}
let readData=(name)=> {
return new Promise((resolve,reject)=>{
//we want to wait for the Promise returned by AsyncStorage.setItem()
//to be resolved to the actual value before returning the value
AsyncStorage.getItem(name).then(r=> resolve(JSON.parse(r)) )
.catch(e=>reject(e))
})
}
//Now you can just read write easily in async function like this:
let fetchedData = await readData("key")
//and for storing data.
storeData("key",object)

Resources