Search code examples
reactjsreactjs-fluxflux

Creating a reusable React.js component with internal events in the Flux architecture


I'm following the "containers and components" approach in the following video to build a reusable component in the Flux architecture.

React.js Conf 2015 (22m 50s): https://youtu.be/KYzlpRvWZ6c?t=22m50s


For example, I'm building an image slider with the 'next' button.

ImageSliderContainer

  • Listens to ImageSliderStore and maintains states (e.g., currentIndex)
  • Renders ImageSlider with props

ImageSlider

  • Stateless component, just rendering based on props
  • Has a child component NextButton

NextButton

  • Stateless component, just rendering based on props
  • Has onClick event

In the Flux architecture, clicking NextButton will send an action to a store. Then, a store will update "currentIndex" and emit a change event. It seems to me that ImageSlider is not reusable anymore as it's tightly coupled with a single store by which a single container will be notified.

Another option will be to add a state "currentIndex" to the ImageSlider component. Clicking NextButton will notify ImageSlider to update its state. But this will introduce a reverse data flow from NextButton to ImageSlider (violating the Flux architecture?). Also, it is against the "containers and components" approach in which a component just renders UI using props.

What will be the best way to make a reusable component in the Flux architecture? More specifically, which element (store, container, component, or something else) should handle the onClick event occurring inside NextButton component?


Edited

Based on answers, here's one solution that satisfies both the Flux architecture and the "containers and components" pattern.

  • The container owns the state "currentIndex." The app may have multiple containers such as ScreenshotSliderContainer and DebugSliderContainer, each of which maintains its own "currentIndex."
  • The container passes the onClick handler to the component ImageSlider as a prop. The onClick handler sends an action to a store.
  • The ImageSlider component is stateless, transferring the onClick handler to a child component NextButton.
  • Consequently, the onClick event in NextButton does not affect a top component ImageSlider. Only the container renders the ImageSlider with new props.

Solution

  • You can pass down the onClick event handler as a prop, like in the react tutorial: http://facebook.github.io/react/docs/tutorial.html#callbacks-as-props