Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 958
PlankTon Avatar asked Jan 17 '18 14:01

PlankTon


2 Answers

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

like image 169
Diogo Sgrillo Avatar answered Oct 19 '22 23:10

Diogo Sgrillo


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.

like image 30
Bojan Ivanac Avatar answered Oct 20 '22 00:10

Bojan Ivanac