bip-bop
bip-bop

Reputation: 1321

If/else statements in React Native

I have a problem with if/else statements in React Native.

For example, I have two states:

onOpen() {
  this.setState({
    index: 1
  });
}

onClose() {
  this.setState({
    index: 0
  });
}

I need to set State index: 0, when toggle close and index: 1, when toggle open.

<TouchableOpacity onPress={() => 
  {index === 0 
    ? navigator.toggleDrawer(this.onClose()) 
    : navigator.toggleDrawer(this.onOpen())
  }
}>

For now, when I click on menu-button I receive index 0 every time, but they should change on 1 and back. Thanks.

Component:

import React from 'react';
import {
  TouchableOpacity,
  Image 
} from 'react-native';

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = {
      index: 0
    };
  }
  onOpen() {
    this.setState({
      index: 1
    });
  }

  onClose() {
    this.setState({
      index: 0
    });
  }

  render() {
    const { index } = this.state;
    return (
   <TouchableOpacity onPress={() => {index === 1 ? 
     navigator.toggleDrawer(this.onClose()) : 
     navigator.toggleDrawer(this.onOpen())}}>
        <Image
        source={require('something.png')}
       />    
   </TouchableOpacity>
    );
  }
}

enter image description here

Upvotes: 1

Views: 4832

Answers (2)

mihai1990
mihai1990

Reputation: 642

The problem is probably that when you close the drawer you don't really press the menu button, but the dark overlay, thus your onPress function is not called. Try to find if there is any event when the drawer is open / closed and set the state in that event instead.

Upvotes: 0

yadhu
yadhu

Reputation: 15642

export default class Home extends Component {
  constructor(props) {
    super(props);
    this.state = { index: 0 };
    this.toggleIndex = this.toggleIndex.bind(this);
  }

  toggleIndex() {
    navigator.toggleDrawer();
    this.setState({ index: this.state.index === 0 ? 1 : 0 });
  }

  render() {
    return (
      <TouchableOpacity onPress={toggleIndex}>
        <Image
          source={require('something.png')}
        />
      </TouchableOpacity>
    );
  }
}

Upvotes: 2

Related Questions