darkermuffin
darkermuffin

Reputation: 999

Calling a method from it's sibling component

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

Upvotes: 0

Views: 852

Answers (2)

Mirodinho
Mirodinho

Reputation: 1321

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.

Upvotes: 1

Alessandro Macanha
Alessandro Macanha

Reputation: 711

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()}

Upvotes: 0

Related Questions