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:
Comment
's state attributes from within CommentForm
or some shared resource (eg: window
scope), which, from my limited understanding, isn't the React WayI'm guessing this is a common problem, but I'm uncertain what the general wisdom is to fix it. Any ideas appreciated.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With