0

Structure

ScreenContainer.js
|
|---Header.js
|     |---LogoButton.js
|
|----FeedContainer.js
      |---Feed.js

I have a FlatList in Feed.js

I want to scrollToOffset() the Feed, when LogoButton is Clicked.

The ref of FlatList exists only in Feed.js

How do I invoke a Feed.js Method from the LogoButton.js ?

EDIT : I tried storing the ref in Redux, but it caused Multiple event dispatches and undefined errors

darkermuffin
  • 919
  • 1
  • 7
  • 16
  • Possible duplicate of [React.js - Communicating between sibling components](https://stackoverflow.com/questions/36143767/react-js-communicating-between-sibling-components) – Michael Hancock Jan 18 '18 at 11:56

2 Answers2

1

There may be multiple solutions here but potentially since you are using Redux you can do the following:

  1. Dispatch an action from Logo.js when the logo is pressed, which sets some state variable isLogoPressed to true.
  2. FeedContainer.js registers with the store and passes down the isLogoPressed prop to Feed.js.
  3. In Feed.js's componentWillReceiveProps() lifecycle method check whether isLogoPressed is true and trigger the ScrollToOffset() function.
  4. Maybe dispatch an action to reset isLogoPressed to false once its done.

This gives you the flexibility of having custom behavior whenever the logo is pressed no matter what screen you are on.

Hope this helps.

Mirodinho
  • 1,171
  • 1
  • 13
  • 25
  • 1
    Oh yes, I could do that. I currently managed to implement by setting a `ref` to the `Feed.js` in the `FeedContainer.js` and then calling a `Feed`'s instance method using that `ref`. Thank you – darkermuffin Jan 19 '18 at 05:33
0

You can use a callback function in your button, just pass the function by props and call it.

Example: on Feed

<LogoButton callback={this.scrollToOffset} />

in the button just use onPress={this.props.callback()}

Alessandro Macanha
  • 711
  • 1
  • 7
  • 20