Switch button in react-native - react-native

Hi I have a problem with the switch button in react-native. I'm using it to toggle or not the activation of push notification. The problem is that if I quit the application, the state of the switch is getting back to false, it's not saving the state ? What am I doing wrong ?
Here is my code :
constructor(props) {
super(props)
this.state = {
switchValue:false
}
}
toggleSwitch = (value) => {
this.setState({switchValue: value})
if(this.state.switchValue){
console.log("Unsubscribed")
} else {
console.log("Subscribed")
}
}
render() {
return (
<SafeAreaView>
<ScrollView>
<View style = {styles.view_container}>
<Text style = {styles.titre}>Notifications</Text>
<Text style = {{marginTop:9}}>Permet de recevoir des alertes lorsque de nouvelles vidéos sont disponibles.</Text>
<View style = {{marginTop: 30, justifyContent:"center", alignContent:"center"}}>
<View style = {styles.row}>
<View style = {styles.row_infos}>
<Image source={require('../Images/couleurs/icons8-belier-100.png')} style = {styles.image}/>
<Text style = {{fontWeight:"bold", fontSize:16,lineHeight:16, color:"#7c4dff"}}>Bélier</Text>
</View>
<Switch
onValueChange = {this.toggleSwitchBelier}
value = {this.state.switchValueBelier}
trackColor={{false:'#000000', true:'#7c4dff'}}
/>
</View>
</View>
</View>
</ScrollView>
</SafeAreaView>
)}

When you quit your Application, all saved variables in the state will be "resetted".
If you would like to keep the state of the toggle button, i would recommend you to use the AsyncStorage, provided by expo.
See here:
https://docs.expo.io/versions/v36.0.0/react-native/asyncstorage/
Just set the item when the toggle-function is triggered like this:
import { AsyncStorage } from 'react-native';
AsyncStorage.setItem('buttonToggle', 'true');
And when you start the application again, load the current status from the AsyncStorage:
const value = await AsyncStorage.getItem('buttonToggle');
if (!!value && value === 'true'){
// Do whatever you like
}

Related

How to use hooks as image's source in react native?

Im making this menu that when the user clicks at an option, it changes the background image, but i cant use the hook that i created as a parameter to the source of the image. Can someone find where im wrong and how to fix it?
Heres the part of my code referents to the menu and the hooks:
export function Home(){
let imagens = {
vovo: '../assets/vovoJuju.png',
mc: '../assets/mcJuju.png',
pato: '../assets/patoJuju.png',
}
const navigation = useNavigation<any>();
const [showBottomSheet, setShowBottomSheet] = React.useState(false);
const [param, setParam] = useState(1);
const [skin, setSkin] = useState('vovo')
const hide = () => {
setShowBottomSheet(false)
}
function handleAbout(){
navigation.navigate('About');
}
useEffect(() => {
if(param==1){
setSkin('vovo');
}
else if(param==2){
setSkin('mc');
}
else if(param==3){
setSkin('pato');
}
})
return(
<SafeAreaView style={styles.container}>
<TouchableOpacity onPress={handleAbout}>
<Counter />
</TouchableOpacity>
<TouchableOpacity onPress={() => {
setShowBottomSheet(true)
}}
>
<Image source={skin} style={styles.imgvj}/>
</TouchableOpacity>
<BottomSheet show={showBottomSheet} height={290} onOuterClick={hide}>
<Pressable onPress={hide} style={styles.bottomSheetContent}>
<Image source={barrinhaLoja} style={styles.barra}/>
</Pressable>
<View style={styles.conteudoLoja}>
<View style={styles.marginLeft48}>
<TouchableOpacity onPress={() => {
setParam(1);
}}>
<Image source={vovoJuju} style={styles.vovo}/>
<Text style={styles.legendasLoja}>Vovó Juju</Text>
</TouchableOpacity>
</View>
<View>
<TouchableOpacity onPress={() => {
setParam(2);
}}>
<Image source={mcJuju} style={styles.mc}/>
<Text style={styles.legendasLoja}>MC Juju</Text>
</TouchableOpacity>
</View>
<View>
<TouchableOpacity onPress={() => {
setParam(3);
}}>
<Image source={patoJuju} style={styles.pato}/>
<Text style={styles.legendasLoja}>Pato Juju</Text>
</TouchableOpacity>
</View>
</View>
</BottomSheet>
I created the "let imagens", "const param", "const skin" and the "useEffect trying" to make this function. I already tried using the source in different ways such as source={skin} and source={imagens[skin]} but it havent worked.
I'm not certain if this solves your problem, but here's how the first few lines of your component should look like without useEffect:
const imagens = {
vovo: '../assets/vovoJuju.png',
mc: '../assets/mcJuju.png',
pato: '../assets/patoJuju.png',
};
export function Home(){
const navigation = useNavigation<any>();
const [showBottomSheet, setShowBottomSheet] = React.useState(false);
const [param, setParam] = useState(1);
const hide = () => {
setShowBottomSheet(false)
}
function handleAbout(){
navigation.navigate('About');
}
let skin = 'vovo';
switch(param) {
case 1: skin = 'vovo'; break;
case 2: skin = 'mc'; break;
case 3: skin = 'pato'; break;
}
return /* the rest goes here */
}
To reference the actual image, you would use something like {imagens[skin]}.
I moved imagens outside of this function because it never changes, but it doesn't impact anything otherwise.

Updating button state which is clicked, inside RenderItem of Flat-list, in React Native

I am new to React Native and trying to accomplish something like below, where simple list from server is rendering in a list with a button. Button, upon click, will be disabled and opacity will be changed.
I am able to create the UI but when I click any button that says Join, previous clicked button resets it state to original. In other words, only one button displays clicked state all the time.
so my code is something like
constructor(props){
super(props);
this.state = {selectedIndices: false, groupsData: ''};
}
Flatlist inside render method looks like
<FlatList style={styles.list}
data={this.state.groupsData}
keyExtractor={(groups) => {
return groups.groupId.toString();
}}
renderItem={(item, index) => {
return this.renderGroupItem(item);
}}/>
RenderGroupItem
renderGroupItem = ({item} )=>(
<GroupItem group = {item} style={{height: '10%'}} onPress = {() => this.onJoinButtonPress(item)}
index = {this.state.selectedIndices}/>
)
onJoinButtonPress
onJoinButtonPress = (item) =>{
this.setState({selectedIndices: true});
}
GroupItem
render(){
if(this.props.group.groupId === this.props.index){
return(
<View style = {[styles.container]}>
<Image source={{uri: 'some Image Url'}} style={styles.roundImage}/>
<Text style={styles.groupText}>{this.props.group.name}</Text>
<View >
<TouchableOpacity style = {[styles.button, {opacity: 0.4}]} activeOpacity = { .5 } onPress = {this.props.onPress}
disabled = {true}>
<Text style = {{color: 'white', fontSize: 12}}>Joined</Text>
</TouchableOpacity>
</View>
</View>
);
}else{
return(
<View style = {styles.container}>
<Image source={{uri: 'Some Image Url'}} style={styles.roundImage}/>
<Text style={styles.groupText}>{this.props.group.name}</Text>
<View >
<TouchableOpacity style = {styles.button} activeOpacity = { .5 } onPress = {this.props.onPress}>
<Text style = {{color: 'white', fontSize: 12}}>Join</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
Now I know that I need to pass an array or hasmap which contains mapping of items that have been clicked but I dont know how to do that. Need desperate help here.
I was able to overcome above problem after maintaining a boolean in the groupsData. Upon selection, I update a boolean "groupsJoined" in groupsData and update the state of groupsData which will invoke render. Inside GroupsItem class, I added a check that if data from props has joinedGroups as true then render selected state else non selected state.
Courtesy https://hackernoon.com/how-to-highlight-and-multi-select-items-in-a-flatlist-component-react-native-1ca416dec4bc

How to use React Native Switch inside a functional component?

I am trying to use the Switch component provided by react-native, but it doesn't toggle.
function settings(props) {
let {changeView, header} = props;
let rememberPin = false;
let toggleRememberPin = (value) => {
rememberPin = value;
};
return (
<View style={styles.appContainer}>
<View style={styles.appBody}>
<View style={{flex:1, flexDirection: 'row',justifyContent:'center',alignItems:'center',width: Dimensions.get('screen').width,backgroundColor: Colors.white}}>
<Text>Remember PIN:</Text>
<Switch
onValueChange={toggleRememberPin}
value={rememberPin}
ios_backgroundColor="#aeaeae"
trackColor={{true: Colors.customerGreen, false: '#aeaeae',}}/>
</View>
</View>
</View>
);
}
I get the Switch rendered in the View, I can touch it and it moves from OFF to ON, but suddently it come back to OFF without keeping on ON state.
What's wrong?
You need to look into the core concepts of React, particularly how component state works.
In short, normal variable assignment doesn't cause a component to re-render and reflect changes. That's when you want to use the concept of state.
Here's how to do it properly:
function Settings(props) {
let {changeView, header} = props;
const [rememberPin, setRememberPin] = useState(false);
const toggleRememberPin = (value) => {
setRememberPin(value);
};
return (
<View style={styles.appContainer}>
<View style={styles.appBody}>
<View style={{flex:1, flexDirection: 'row',justifyContent:'center',alignItems:'center',width: Dimensions.get('screen').width,backgroundColor: Colors.white}}>
<Text>Remember PIN:</Text>
<Switch
onValueChange={toggleRememberPin}
value={rememberPin}
ios_backgroundColor="#aeaeae"
trackColor={{true: Colors.customerGreen, false: '#aeaeae',}}/>
</View>
</View>
</View>
);
}

onChangeText of InputField issue in React Native

I am working on a ReactNative application. I have some input fields, on button click if any of these fields is empty i have to show validation error. My code is:
<View>
<InputField placeholder="Teilnummer"
onChangeText={(nm)=> this.setState({pTeilnummer: nm})}
/>
<View>
{
this.state.ErrorTeilnummer ? <Text style={styles.ValidationErrorMessage}> * Required </Text> : null
}
</View>
<InputField placeholder="Teilbenennung"
onChangeText={(nm)=> this.setState({pTeilbenennung: nm})}
/>
<View>
{
this.state.ErrorTeilbenennung ? <Text style={styles.ValidationErrorMessage}> * Required </Text> : null
}
</View>
<InputField placeholder="Lieferant"
onChangeText={(nm)=> this.setState({pLieferant: nm})}
/>
<View>
{
this.state.ErrorLieferant ? <Text style={styles.ValidationErrorMessage}> * Required </Text> : null
}
</View>
<Button title="Speichern" color="#ee7100" onPress={() => { this._addProject(this.state.pTeilnummer + "_" + this.state.pTeilbenennung + "_" + this.state.pLieferant, this.state.pdate)}}/>
</View>
I have declared these states as:
constructor(props){
this.state = {ErrorTeilbenennung: false, ErrorTeilnummer: false, ErrorLieferant: false pTeilbenennung: null, pTeilnummer: null, pLieferant: null};
My button click code is:
_addProject = (name, date) =>{
teilbenennung = this.state.pTeilbenennung;
teilnummer = this.state.pTeilnummer;
lieferant = this.state.pLieferant;
var selectedCheck = this.state.addCheck
if(teilbenennung == null || teilnummer == null || lieferant == null)
{
if(teilbenennung == null)
this.setState({ErrorTeilbenennung: true})
else
this.setState({ErrorTeilbenennung: false})
if(teilnummer == null)
this.setState({ErrorTeilnummer: true})
else
this.setState({ErrorTeilnummer: false})
if(lieferant == null)
this.setState({ErrorLieferant: true})
else
this.setState({ErrorLieferant: false})
}
else
{ // saving to database
}
}
When i click on the button first time i get the required validation errors. But after i type something in the first InputField and presses the button, i still get the validation error against that field (may be there is some issue with "onChangeText"), but if i click the button again then the validation error against that field is removed (i mean i have to click twice). Let me add one more thing, when i click on the InputField to write something in it the component reloads. How can i remove this issue so that it works fine with single click
I made an example to solve your problem. This is how you solve the problem you want.
Comparing the status values separately is a very inconvenient way. We can solve this problem sufficiently through onChangeText
Example is here ExampleLink
import React, { Component } from 'react';
import { AppRegistry, TextInput,View,Text,Button } from 'react-native';
export default class UselessTextInput extends Component {
constructor(props) {
super(props);
this.state = {
text: '',error1 : "error1" ,
text2: '',error2 : "error2" };
}
checkfunc() {
if(this.state.text !== '' && this.state.text2 !== ''){
alert("sucess");
} else {
alert("faild");
}
}
render() {
return (
<View style={{flex:1,alignItems:"center" , justifyContent:"center"}}>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text) => this.setState({text})}
value={this.state.text}
/>
{this.state.text !== '' ? null : (<Text>{this.state.error1}</Text>)}
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1}}
onChangeText={(text2) => this.setState({text2})}
value={this.state.text2}
/>
{this.state.text2 !== '' ? null : (<Text>{this.state.error2}</Text>)}
<Button title="checkinput" onPress={() => this.checkfunc()}/>
</View>
);
}
}
// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput);
Issue was that my view was inside KeyboardAwareScrollView, so the first click closes the keyboard, that's why my button click does not trigger on first click. This can be resolved in two ways:
Use ScrollView instead of KeyboardAwareScrollView
Set keyboardShouldPersistTaps to true like this:
<KeyboardAwareScrollView keyboardShouldPersistTaps={true}>

Not able to set active and inactive images in React Native

I am showing custom tab-bar in my application which is showing at centre of the screen. So, Each time one tab should be active and other tabs will be inactive state.
According to that, I have implemented logic(bool values) and tried to change images, But, It's not working.
My requirement is
I have 4 tabs, suppose if user tap on 1st tab, I have to set active
image to 1st tab then rest of 3 tabs with inactive images according to
those titles (different inactive) images.
Its like for all tabs active and inactive states, each time one tab
only active state.
It's showing undefined and even if and else if conditions executing, But, nothing changing images.
Here is my code
constructor(props) {
super(props);
// this.state = { dataArray: getListData()}
this.state = { selectedTab: 'Value', flagImage:true, flagForTelugu: false, flagForTamil: false, flagForHindi: false, flagForEnglish: false}
}
OnTabItemHandler = (tabItem) => {
this.setState({selectedTab: tabItem,flagImage:this.state.flagImage})
}
renderBottomContent = (item) => {
const {selectedTab, dataArray, flagForTelugu, flagForTamil, flagForHindi, flagForEnglish} = this.state
this.state = { dataArray: getListData()}
if (selectedTab === ‘Telugu’) {
this.flagForTelugu = true
this.flagForTamil = false
this.flagForHindi = false
this.flagForEnglish = false
} else if (selectedTab === ‘Tamil’) {
this.flagForTamil = true
this.flagForTelugu = false
this.flagForHindi = false
this.flagForEnglish = false
} else if (selectedTab === ‘Hindi’) {
this.flagForHindi = true
this.flagForTamil = false
this.flagForTelugu = false
this.flagForEnglish = false
} else if (selectedTab === ‘English’) {
this.flagForEnglish = true
this.flagForTamil = false
this.flagForTelugu = false
this.flagForHindi = false
}
//loading some other text here in bottom
}
render(item) {
const {selectedTab, flagForTelugu, flagForTamil, flagForHindi, flagForEnglish} = this.state;
return (
<View style={styles.container}>
<View style = {styles.tabContainer}>
<TouchableOpacity style={styles.tabIcons} onPress={() => this.OnTabItemHandler(‘Telugu’)}>
<Image
style={styles.tabItemsImages}
source={this.state.flagImage === true ?
teluguActiveImage :
teluguDeActiveImage}
/>
</TouchableOpacity>
<Text style={styles.tabTextItems} onPress={() => this.OnTabItemHandler('Telugu')}>Telugu</Text>
</View>
<View style = {styles.tabContainer}>
<TouchableOpacity style={styles.tabIcons} onPress={() => this.OnTabItemHandler(‘Tamil’)}>
<Image
style={styles.tabItemsImages}
source={this.state.flagImage === true ?
tamilActiveImage :
tamilDeActiveImage}
/>
</TouchableOpacity>
<Text style={styles.tabTextItems} onPress={() => this.OnTabItemHandler('Tamil')}> Tamil </Text>
</View>
<View style = {styles.tabContainer}>
<TouchableOpacity style={styles.tabIcons} onPress={() => this.OnTabItemHandler(‘Hindi’)}>
<Image
style={styles.tabItemsImages}
source={this.state.flagImage === true ?
hindiActiveImage :
hindiDeActiveImage}
/>
</TouchableOpacity>
<Text style={styles.tabTextItems} onPress={() => this.OnTabItemHandler('Hindi')}> Hindi </Text>
</View>
<View style = {styles.tabContainer}>
<TouchableOpacity style={styles.tabIcons} onPress={() => this.OnTabItemHandler(‘English’)}>
<Image
style={styles.tabItemsImages}
source={this.state.flagImage === true ?
englishActiveImage :
englishDeActiveImage}
/>
</TouchableOpacity>
<Text style={styles.tabTextItems} onPress={() => this.OnTabItemHandler('English')}> English </Text>
</View>
</View>
{this.renderBottomContent(item)}
</View>
);
}
Can anyone suggest me, Where I am doing wrong?
And in the method renderBottomContent(), these flagForTelugu,
flagForTamil, flagForHindi, flagForEnglish showing as undefined while
debugging time.
I'm not good to explaining how the code works.
but the idea is you need 1 state called selectedIndex and the rest is you need to check the active image with the selectedIndex is match show the active image
the example code may looks like this:
import React, { Component } from 'react';
import RN from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state={
selectedIndex:0,
//you can change every urlActive and urlInactive url to your needed image
tabList:[
{label:'tab 1', urlActive:'https://livelovely.com/static/images/full-listing/icon-modal-success%402x.png', urlInactive:'https://icon2.kisspng.com/20180823/ioc/kisspng-traffic-sign-image-traffic-code-no-symbol-inactive-symbol-www-pixshark-com-images-gallerie-5b7e884790b8a3.5710860815350190795928.jpg'},
{label:'tab 2', urlActive:'https://livelovely.com/static/images/full-listing/icon-modal-success%402x.png', urlInactive:'https://icon2.kisspng.com/20180823/ioc/kisspng-traffic-sign-image-traffic-code-no-symbol-inactive-symbol-www-pixshark-com-images-gallerie-5b7e884790b8a3.5710860815350190795928.jpg'},
{label:'tab 3', urlActive:'https://livelovely.com/static/images/full-listing/icon-modal-success%402x.png', urlInactive:'https://icon2.kisspng.com/20180823/ioc/kisspng-traffic-sign-image-traffic-code-no-symbol-inactive-symbol-www-pixshark-com-images-gallerie-5b7e884790b8a3.5710860815350190795928.jpg'},
]
}
}
render() {
console.disableYellowBox = true;
return (
<RN.View style={{flex:1}}>
//creating the tab height
<RN.View style={{flex:0.07, flexDirection:'row'}}>
{
//loop throught the state
this.state.tabList.map((item,index)=>{
return(
//the style just to make it beautiful and easy to debug
<RN.TouchableOpacity style={{flex:1, alignItems:'center', backgroundColor:index==0?'green':index==1?'blue':'yellow'}}
//this onpress to handle of active selected tab
onPress={()=>{this.setState({selectedIndex:index})}}
>
<RN.View>
<RN.Text>{item.label}</RN.Text>
<RN.Image
//here's the magic show off
source={{uri:this.state.selectedIndex==index?item.urlActive:item.urlInactive}}
style={{width:20, height:20, resizeMode:'contain'}}
/>
</RN.View>
</RN.TouchableOpacity>
)
})
}
</RN.View>
</RN.View>
);
}
}
and the result look like :