Dina
Dina

Reputation: 111

checkbox toggle doesn't work correctly react native

I have this checkbox example

constructor(props) {
    super(props);
    this.state = {
    check: true,
    };}

checkBoxtTest(){
this.setState(
 {check:!this.state.check})}

on return

 <CheckBox
    value={this.state.check} onChangee={()=>this.checkBoxtTest()}
/> 

when i press again in checkbox the value doesn't change

Upvotes: 1

Views: 3436

Answers (3)

Seema
Seema

Reputation: 41

import React, { Component } from 'react';
import { Container, Content, ListItem, CheckBox, Text, Body } from 'native-base';
export default class App extends Component {

    constructor(props) {
        super(props);
        this.state = {
            checked: true
        }
    }

    render() {
        return (
            <Container>
                <Content>
                    <ListItem>
                        <CheckBox
                            checked={this.state.checked}
                            onPress={() => this.setState({checked: !this.state.checked})}
                        />
                        <Body>
                        <Text>Finish list Screen</Text>
                        </Body>
                    </ListItem>
                </Content>
            </Container>
        );
    }
}

Upvotes: 0

you are having a typo 'onChange'

<CheckBox
    value={this.state.check} onChange={()=>this.checkBoxtTest()}
/> 

If you are using state for changing state follow this way

this.setState((prevState) => ({check: !prevState.check}))

You can use arrow function instead of normal function

checkBoxtTest = () => {
    this.setState((prevState) => ({check: !prevState.check}));
}

Upvotes: 1

CodeZombie
CodeZombie

Reputation: 2087

Firstly,change it to onChange.And your checkBoxTest should be bind in the constructor as it is recommended as best practice.

constructor(props) {
    super(props);
    this.state = {
    check: true,
    };
    this.checkBoxtTest = this.checkBoxtTest.bind(this);
}

checkBoxtTest(){
  this.setState({
    check : !this.state.check
  })
}

<CheckBox value={this.state.check} onChange={this.checkBoxtTest()} /> 

Upvotes: 0

Related Questions