Shreepad V
Shreepad V

Reputation: 41

How to access a state to other class in react native?

I want to access the state declared in MainActivity class to the class Hamburgicon. The state of mainactivity class can be accessed in the same class and please tell me how to access the state in other classes or the whole project.

Upvotes: 2

Views: 1947

Answers (1)

Kosalram Ramakrishnan
Kosalram Ramakrishnan

Reputation: 818

You can send your state as props from MainActivity to other classes or functional components. In your case for instance:

HamburgerIcon = (props) => {
   return (
     <View style={{flexDirection: 'row'}}>
       <TouchableOpacity 
         onPress={this.toggleDrawer.bind(this)} 
       >
         <Text>{props.item}</Text>
       </TouchableOpacity>
     </View>
   );
}

class MainActivity extends Component {
  constructor(props) {
    super(props);
    this.state = {
        a: 'ABCD'
    };
  }

  render()
  {
    return(
      <View style = { styles.MainContainer }>
        <Text> this.state.a </Text>
        <HamburgerIcon item={this.state.a}/>    
      </View>
      );
   }
}

Upvotes: 4

Related Questions