React newbie: sharing state across unlinked components
Asked Answered
B

2

8

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.

Beckmann answered 17/1, 2018 at 14:0 Comment(0)
F
6

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

Flick answered 17/1, 2018 at 14:22 Comment(1)
I took a night to work through Redux, and it's clearly the right solution. Many thanks.Beckmann
V
2

Redux is the perfect use case for this honestly. It doesn't take too long to implement but if you've never done it before you're gonna need a day or two to wrap your head around it.

In general, as your project grows even more, you will have a much easier time managing one state instead of a thousand component wide states.

So, if you're gonna have more situations like this, or situations where you have to pass down props through more than 3 components. I'd implement Redux now and be future proof.

Vadose answered 17/1, 2018 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.