What is the best way to share a user object between multiple react_component
other than hanging it off of window?
For example -
<%= react_component("HelloWorld1", { user: @user }) %>
<%= react_component("HelloWorld2", { user: @user }) %>
What is the best way to share a user object between multiple react_component
other than hanging it off of window?
For example -
<%= react_component("HelloWorld1", { user: @user }) %>
<%= react_component("HelloWorld2", { user: @user }) %>
Copyright © 2021 Jogjafile Inc.
If you're using React and HTML.ERB for the frontend
I think the way you currently have it is the best way to do it if you want to combine HTML.ERB and React.
Just as you can't pass down a prop to two components at once when dealing with pure React, I don't think you can do it in this case too.
If you're only using React for the frontend
Note: I'm not sure how the following would affect SEO.
You could use the Rails app as an API, and display your React app using a single HTML tag in
static_pages#root
(or similar). And then usereact-router-dom
for routing and changing pages on the frontend.That way you don't have to keep rendering
html.erb
templates that you may pass instance variables to. You'd be fetching data and modifying it using API requests.Extra details
If you choose to do the second method (using
react-router-dom
), then the files might look something similar to the following:routes.rb
app/controllers/static_pages_controller.rb
app/views/static_pages/root.html.erb
app/javascript/components/App.jsx