React checkbox check, but doesn't uncheck - react-native

I'm creating app in React Native and I need checkbox there. I can check a checkbox, but I cannot uncheck it.
I'm using state to know, if it's checked/unchecked.
import { CheckBox } from 'react-native';
this.state = {
checked: false,
}
<CheckBox value={this.state.checked} onValueChange={() => this.setState({ checked: !this.state.checked })} />
I was expecting, that this.setState({ checked: !this.state.checked })} will negate this.state.checked but it's doesn't seems like that.

This code is working for me.
import * as React from 'react';
import { Text, View, CheckBox } from 'react-native';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
checked: false
};
}
render() {
return (
<View>
<CheckBox
value={this.state.checked}
onValueChange={() => this.setState({ checked: !this.state.checked })}
/>
</View>
);
}
}

I dont know from where are you imported that checkbox, but for example: https://react-native-training.github.io/react-native-elements/docs/checkbox.html
This needs a prop checked, but not a prop value
In your case:
<CheckBox checked={this.state.checked} onValueChange={() => this.setState({ checked: !this.state.checked })} />

Related

Unable to close the DateTimePickerModal after setting the time in ReactNative

I am learning to set the time in ReactNative.
I was able to set the time with the onConfirm process of DateTimePickerModal, but I am having trouble closing the DateTimePicker at the same time.
Here is the source.
import React, {Component} from 'react';
import{
Text,
View,
Button,
}from 'react-native';
//import DateTimePicker from '#react-native- community/datetimepicker';
import DateTimePickerModal from "react-native-modal-datetime-picker";
export default class App extends Component<{}>{
constructor(){
super()
this.state={
vibrate: false,
date: new Date(),
isShowDatePicker: false
}
}
render(){
var {date} = this.state
return (
<View style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: "F5FCFF"
}}>
<Text>{date.getFullYear()}Y {date.getMonth() + 1}M {date.getDate()}D</Text>
<Button
title={'Press'}
onPress={() => this.setState({ isShowDatePicker: !this.state.isShowDatePicker })} />
<DateTimePickerModal
isVisible={this.state.isShowDatePicker}
mode="date"
date={this.state.date}
onConfirm={
date=>{this.setState({date})}
}
onCancel={() => this.setState({ isShowDatePicker: !this.state.isShowDatePicker })}
headerTextIOS='Please Select Date'
confirmTextIOS='OK' />
</View>
);
}
}
I would like to write the process in OnConfirm like this, but I can't do it.
onConfirm={
date=>{this.setState({date})},
() => this.setState({ isShowDatePicker: !this.state.isShowDatePicker })
}
This description only closes the window and does not set the time.
I would appreciate it if someone could tell me how to do this.
Write your onConfirm like this..This would close the modal
onConfirm={(data) => {
this.setState({date})
this.setState({ isShowDatePicker: false })
}
Also your onCancel like this
onCancel={() => this.setState({ isShowDatePicker: false })}
Don't set the state to !isShowDatePicker as we know onCancel and onConfirm we need to close the modal..so set it to false rather than setting it to !isShowDatePicker
Also change your Button onPress to this
<Button
title={'Press'}
onPress={() => this.setState({ isShowDatePicker:true })} />
See working example here

Show component when clicking the button React Native

in the file popUpDialog.Js
export default class DialogTester extends Component {
constructor(props) {
super(props)
this.state = {
dialogVisible: false
};
}
showDialog = () => {
this.setState({ dialogVisible: true });
};
handleCancel = () => {
this.setState({ dialogVisible: false });
};
handleRedefinir = () => {
this.setState({ dialogVisible: false });
};
handleEmail = (email) => {
console.log(email);
}
render() {
const {dialogVisible} = this.state;
return (
<View>
<Dialog.Container visible={this.state.dialogVisible}>
<Dialog.Title>Redefinir Senha</Dialog.Title>
<Dialog.Description>
Digite seu e-mail cadastrado
</Dialog.Description>
<Dialog.Input placeholder="E-mail" onChangeText={(email) => this.handleEmail(email)}
></Dialog.Input>
<Dialog.Button label="Cancelar" onPress={this.handleCancel} />
<Dialog.Button label="Redefinir" onPress={this.handleRedefinir} />
</Dialog.Container>
</View>
);
}
}
so far all right
in the file Index.js
import React, { Component } from "react";
import {
View,
TextInput,
Text,
TouchableOpacity,
SafeAreaView,
StatusBar,
} from "react-native";
import styles from "./styles";
import PopUp from "../Login/popUpDialog";
export default class Login extends Component {
render() {
return (
<SafeAreaView>
<TouchableOpacity
onPress={() => <PopUp dialogVisible = true /> } //It does not work
style={styles.redefinirButton}
>
<Text style={styles.textRedefinirButton}>Redefinir Senha</Text>
</TouchableOpacity>
</SafeAreaView>
);
}
}
How do I make dialogVisible = true when I press it?
I try props and setState don't work
Everything else works, if I try to put out of onPress and leave the variable as true as default it shows, but when I leave it false and try to pass true when I press the button I can't do it in any way.
You need to keep the state of the visibility in the parent component (Login) and pass it as a prop to the Popup component. Then, in the Popup component just use props.dialogVisible where you need it

Why doesn't checkbox work in React Native?

import CheckBox from '#react-native-community/checkbox';
export default class All extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [],
isSelected: true,
};
}
checkBoxChanged() {
alert('changed');
this.setState({isSelected : !this.state.isSelected})
}
render() {
const { items } = this.state;
return (
<Content>
<View>
{items.map((item) => (
<View>
<Text>{item.name}</Text>
<CheckBox
value={this.state.isSelected}
onValueChange={() => this.checkBoxChanged()}
/>
</View>
))}
</View>
</Content>
);
}
}
This doesn't work.I mean nothing happens.
When I check on, nothing changes and it doesn't reach to checkBoxChanged().
I got stuck in this problem.
I would appreciate it if you could help me :)
You can use onValueChange={() => checkBoxChanged()}
<CheckBox
value={this.state.isSelected}
onValueChange={() => checkBoxChanged()}
/>
And in checkBoxChanged function you can set the state to change the value of isSelected
checkBoxChanged(){
this.setState({isSelected : !this.state.isSelected})
}
Moreover the checkbox has been deprecated you have to install
#react-native-community/checkbox
check this link to know more.
Hope this helps
import { CheckBox } from 'react-native';
isChecked = false
checkBoxChanged() {
alert('changed');
}
getCheckedStatus(){
this.isChecked != this.isChecked;
return this.isChecked;
}
<CheckBox
activeOpacity={1}
textStyle={{ color: colors.colorGray, fontSize: dimen.fontSize.textAppearanceBody1_16 }}
containerStyle={styles.checkBoxContainer}
checkedColor={colors.profileTabSelectedColor}
uncheckedColor={colors.profileTabSelectedColor}
title={'Gender'}
checked={this.getCheckedStatus()}
onPress={() => { this.checkBoxChanged() }}
/>
I would like to tell you don't use checkbox from react-native it is deprecated, still if you are using it please see the below code, there is no onChange Prop, use onValueChange instead of onChange, and maintain a state and pass value prop to checkbox component.
https://reactnative.dev/docs/checkbox#__docusaurus
import React, { useState } from "react";
import { CheckBox, Text, StyleSheet, View } from "react-native";
export default App = () => {
const [isSelected, setSelection] = useState(false);
return (
<View style={styles.container}>
<View style={styles.checkboxContainer}>
<CheckBox
value={isSelected}
onValueChange={setSelection}
style={styles.checkbox}
/>
<Text style={styles.label}>Do you like React Native?</Text>
</View>
<Text>Is CheckBox selected: {isSelected ? "👍" : "👎"}</Text>
</View>
);
};
The code should be
import { CheckBox } from 'react-native';
checkBoxChanged() {
alert('changed');
}
<CheckBox onValueChange={()=>this.checkBoxChanged()} />
You are calling the function directly instead of calling it on click.
This checkbox works only in Android so better use the one from react-native elements
https://react-native-elements.github.io/react-native-elements/docs/checkbox.html
Checkbox are being deprecated from react-native-element but it can be used from react native component.
to use them.
Install : npm install #react-native-community/checkbox --save
Usage:
import CheckBox from '#react-native-community/checkbox';
Inside you use this element
<CheckBox value={this.state.check}
onChange={()=>this.checkBoxText()} />
And inside your class
constructor(props) {
super(props);
this.state = {
check: false
};
Declare a function outside your constructor area.
create:
checkBoxText() {
this.setState({
check:!this.state.check
})
alert("Value Changed to " + this.state.check)
}
It will create your clickable Check-box on your application.

React Native Checkbox not working

I have my react-native app consisting of a form. I have implemented two check-boxes with their state set to boolean true. I want boolean true or false to get submitted to the database from those check-boxes but the check-box button won't work.
Here's my code:
import React, { Component } from 'react';
import { View, Text, Button, TextInput, StyleSheet } from 'react-native';
import { CheckBox } from 'react-native-elements';
import axios from 'axios';
export default class Delivery extends Component {
constructor(props) {
super(props);
this.state = {
trackingNo: '',
weight: '',
length: '',
width: '',
//checked: true,
delivered: { checked: true }
};
}
componentDidMount(){
fetch('https://courierapp-test.herokuapp.com/products/')
.then(
function(response) {
if (response.status !== 200) {
console.log('Looks like there was a problem. Status Code: ' +
response.status);
return;
}
// Examine the text in the response
response.json().then(function(data) {
console.log(data);
});
}
)
.catch(function(err) {
console.log('Fetch Error :-S', err);
});
}
onPressSubmit(){
axios.post('https://courierapp-test.herokuapp.com/products/', {
requestId: this.state.trackingNo,
parcelWeight: this.state.weight,
parcelLength: this.state.length,
parcelWidth: this.state.width,
parcelPickup: this.state.pickup,
parcelDelivered: this.state.delivered,
})
.then(function (response) {
console.log(response, "data sent");
})
.catch(function (error) {
console.log(error, "data not sent");
});
}
render() {
return (
<View style={{padding: 15}}>
<TextInput
style={styles.inputStyle}
placeholder="Request Id"
onChangeText={(trackingNo) => this.setState({trackingNo})}
value={this.state.trackingNo}
/>
<CheckBox style={styles.checkStyle}
title='Pickup'
checked={this.state.checked}
/>
<CheckBox style={styles.checkStyle}
title='Delivered'
onValueChange={() => this.setState({ checked: !this.state.checked })}
/>
<TextInput
style={styles.inputStyle}
placeholder="Enter Parcel Weight(Kg)"
onChangeText={(weight) => this.setState({weight})}
value={this.state.weight}
/>
<TextInput
style={styles.inputStyle}
placeholder="Enter Parcel Length(Cm)"
onChangeText={(length) => this.setState({length})}
value={this.state.length}
/>
<TextInput
style={styles.inputStyle}
placeholder="Enter Parcel Width(Cm)"
onChangeText={(width) => this.setState({width})}
value={this.state.width}
/>
<Button
onPress={() => {
this.onPressSubmit()
}
}
title="Submit"
color="#1ABC9C"
/>
</View>
);
}
}
const styles = StyleSheet.create({
inputStyle: {
color: '#1ABC9C',
height: 40,
borderWidth: 0
}
});
I have tried every work around but could not solve it. the checkbox keeps on blinking only upon clicking but could not change the state checked or unchecked and also no value getting submitted to database.
Define variable checked in state
this.state = {
checked: false
};
create a method
onChangeCheck() {
this.setState({ checked: !this.state.checked})
}
And use onChange() prop of Chekbox to update the state and provide value to the check box like this
<CheckBox
style={styles.checkBox}
value={this.state.checked}
onChange={() => this.onChangeCheck()} />
Try changing value inside event onValueChange
<CheckBox value={this.aBooleanField} onValueChange={() => {
this.aBooleanField = !this.aBooleanField;
this.updateView();
}}/>
The updateView is like this:
updateView() {
this.setState({ viewChanged: !this.state.viewChanged})
}
Also works for < Switch /> component, and you can use updateView to only to refresh the view, setState it's to keep state values (when you resume app, rotate screen, etc).

How to change state when Button pressed?

I'm new to React Native and unfamiliar with js.
I want the program to show what I wrote in TextInput when I pressed the Button (there's a Text below the Button). I figured maybe I should make two state: put state1 text as Text input, and put state2 mimin as TextInput input, and when Button pressed, put state2 mimin to state1 text.
I've tried with the code below but it gave me Red Page when I click the Button.
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
Button,
TextInput,
Alert,
View
} from 'react-native';
export default class Hella extends Component {
constructor(props) {
super(props);
this.state = {text: '', mimin: ''};
}
render() {
return (
<View style={styles.container}>
<TextInput
style={{height: 40}}
placeholder="Type here to translate!"
onChangeText={(mimin) => this.setState({mimin})}
/>
<Button
onPress={onButtonPress}
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
/>
<Text style={styles.instructions}>
{this.state.text}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#F5FCFF',
}
});
const onButtonPress = () => {
Hella.setState({
text: Hella.state.mimin -------> where the error happened
});
};
AppRegistry.registerComponent('Hella', () => Hella);
The error was
undefined is not an object (evaluating 'Hella.state.mimin')
onButtonPress
<project location>/index.android.js:61
What did I do wrong? How should I declare it? Where can I learn more?
Your onButtonPress should be inside class since you want to do setState
export default class Hella extends Component {
constructor(props) {
...
}
onButtonPress = () => {
this.setState({
text: this.state.mimin
});
}
render() {
return (
...
<Button
onPress={this.onButtonPress}
...
/>
...
);
}
}
React Native uses a lot of React concepts. Learning basics of React will help you a lot https://facebook.github.io/react/tutorial/tutorial.html
The function definition should be like below.
onButtonPress = () => {
this.setState({
text: this.state.mimin
});
}