2

I have a Searchbar component within react-native that is imported within a parent component,

The SearchBar child component has the following element:

         <Search
            ref={component => this._search = component}
            onChangeText={this.searchUpdated} 
            blurOnSubmit
            useClearButton={false}
            backgroundColor='#15A5E3'
          />
         searchUpdated(term) {
          return new Promise((resolve, reject) => {
          this.setState({ searchTerm: term });
          resolve();
         });
        }

Is is possible to access the state of this child component within the parent in which it is imported? Thanks in advance fo the help

pj013
  • 1,393
  • 1
  • 10
  • 28
  • do a console.log of the ref component: `console.log(this._search);`. You should be able to look for the state there. – Rodius Jun 11 '18 at 14:49
  • It is possible but would be a hack. There's almost definitely a better way for you to do it, like passing the change to the parent using a callback function. Could be better if you explained what you're trying to accomplish instead. – Raicuparta Jun 11 '18 at 14:55
  • Possible duplicate of [Access child state of child from parent component in react](https://stackoverflow.com/questions/49558824/access-child-state-of-child-from-parent-component-in-react) – GauthierG Jun 11 '18 at 15:30

1 Answers1

0

You can set the 'ref' prop of any react component, and then inside the Parent component you can access any methods from the child like this:

this.refs.child.childMethod()

An example:

Child Component

class ChildComponent extends Component {

   getState() {
    return this.state
   }

   render() {
    return <Text>I'm a child</Text>
   }
}

Parent Component:

class ParentComponent extends Component {

   manipulateChildState() {
    let child = this.refs.childRef.getState()
    // do something here
   }

   render() {
    return <Child ref='childRef' />
   }
}

Just remember to use the same String on this.refs.REFERENCE and on the prop ref='REFERENCE'

Lucas Fabre
  • 1,806
  • 2
  • 11
  • 25