Search code examples
ruby-on-railsreactjsreact-reduxreact-on-rails

React newbie: sharing state across unlinked components


I'm a React newbie trying to integrate React into a Rails site. I have a CommentForm component at the very top of the page/html, and a Comments component at the bottom of the same page. At present, both are rendered through React-On-Rails' react_component method.

The problem is that, upon submitting a form in CommentForm, I'd like to change this.state.comments in the Comments component. I'm familiar with the idea of ensuring state is bubbled up to a common parent component, but at present, these two components don't have a common parent (or any parents at all).

So, with the disclaimer that I've been learning React for all of 2 days and am likely very confused, what's best practice for overcoming this sort of issue? Options as I see them:

  • Rewrite the entire rails view as a single parent component with the two components as children underneath. This doesn't sound fun - there's a lot of html generated by a lot of rails helpers between the two components on the page
  • Use Redux to create a store that's shared between the two components(???)
  • Somehow create a parent component while still rendering the two other components in separate parts of the page(?)
  • Accessing Comment's state attributes from within CommentForm or some shared resource (eg: window scope), which, from my limited understanding, isn't the React Way

I'm guessing this is a common problem, but I'm uncertain what the general wisdom is to fix it. Any ideas appreciated.


Solution

  • The first option would be doing the react way only (with no external libraries). If your project it's not that big, could be a solution.

    The third and fourth option are definitely not the way to go.

    For what you said, using Redux seems to be the easiest solution.

    The Comments component should be drawing all the comments in your global store and the CommentForm should add the comments to the store (and probably send an AJAX request for saving server side also).

    Then, these components will share the same Provider and have access to same Store.

    I'd suggest you watching Dan's Course