raph
raph

Reputation: 319

"Error: this.setState is not a function" Trying to uncheck CheckBox in React Native?

I'm trying to implement React Native's CheckBox component but can't seem to get it unchecked after changing its value the first time- it's perpetually checked. I understand that the value prop must be set for it to reflect user actions, so I'm trying to setState onChange... what am I getting wrong? :/

export const ReviewCardCheckBox = (props) => {

    this.state = { checked: false };

    return (

            <View style={styles.sectionStyle}>

                    <View style={{justifyContent: 'flex-start', flex:1}}>
                        <Text style={styles.fontStyle}>{props.option}</Text>
                    </View>

                <View style={{flexDirection: 'row', justifyContent: 'flex-end', flex:1}}>
                    <CheckBox onChange={ () => this.setState(  {checked: !this.state.checked} )}/>
                </View>
            </View>

        )
};

Thanks for the help!

Upvotes: 1

Views: 509

Answers (3)

vicky patel
vicky patel

Reputation: 705

export class ReviewCardCheckBox extends React.Component{
      constructor(props){
          super(props);
          this.state = {chacked: false};
      }
      render(){
          return (
              //do something here
          );
      }
}

Upvotes: 0

Jo&#227;o Cunha
Jo&#227;o Cunha

Reputation: 10307

What you have is a stateless functional component. The purpose of these components is just to receive props and do something with them.

Learn more about the difference here

This function is a valid React component because it accepts a single “props” (which stands for properties) object argument with data and returns a React element. We call such components “functional” because they are literally JavaScript functions.

For you to have state you must do

class ReviewCardCheckBox extends React.Component {
  constructor(props) {
     super(props);
     this.state = { checked: false };
  }

  render() {
    // do what you want.
  }
}

Upvotes: 2

Daniel Tran
Daniel Tran

Reputation: 6169

You are declaring a Stateless component (a function) so this Component can't have state, as well as it can't setState.

Declare the Component as class instead.

Upvotes: 0

Related Questions