PuskarShestha
PuskarShestha

Reputation: 855

How to access the state of one component from the other?

In my react-native application i have a input form component and a button component. I want to send the login information to my server when user presses the button but the data is present in the form component.

How can i access the state of the form from the button component.

Upvotes: 2

Views: 64

Answers (1)

Allan Chua
Allan Chua

Reputation: 10175

A smarter way to solve your problem is to expose an onclick property on the button component and feed it with the event attached to the form object. Send an AJAX request to the server and your problem is solved.

Sample Button Component

  import React from 'react';

  class PokePagerButton extends React.Component {
      render() {
          let {text, tooltip, onClick, currentPage, value, isVisible = true} = this.props;

          return(
              <button className={'poke-pager-button ' 
                                      + (currentPage === text ? ' active' : ' ')
                                      + (isVisible ? ' ' : ' hidden')}
                      onClick={onClick}
                      title={tooltip}
                      value={value}>{text}</button>
          );
      }
  }

  export default PokePagerButton;

Sample Consumption

 class PokeForm extends React.Component {
   onPagerButtonClick() {
       const request = await fetch ('/echo/json', {
            headers: {
                'Content-type': 'application/json'
            },
            method: 'POST',
            body: { a: this.state.pokedata }
      });
   }
   render() {
      <PokepagerButton onClick={this.onPagerButtonClick} />
   }
 }

Upvotes: 1

Related Questions