react-rails
react-rails copied to clipboard
Is there a way to pass a context object to react_component
Steps to reproduce
The current syntax for react_component doesnt let you specify context.
Expected behavior
To be able to pass an object that would act as the context for the rendered component.
Actual behavior
React component has no context when rendered.
Im having a similar problem, and we endup building a wrapContext
function, that takes creates a higher order component and extracts context
from props, it works but it feels hacky coz it seems like this is something that should be done by the framework.
What is the use case for passing in a context to the render_component helper? Are you referring to the same context that is set by default here?: https://github.com/reactjs/react-rails/blob/master/lib/generators/react/install_generator.rb#L99
@3den I'd be interested in seeing your solution if possible so that I can understand more about the use case and look for possible ways to help :)
The react context is just meant to be an object such that all the child components in the tree can access. Its usually acts like a global variable that is set at the top level component and is treated like a read-only global in the children without having to explicitly pass them down as a prop. Popular libraries like react-router use it as well.
@BookOfGreg Is it possible for react_component to take a render prop, this way i can use react_component to render a provider component and have it render this.props.render
erb
<%= react_component "Provider", {render: 'ProductPage', context: {foo: 'bar'}} %>
Provider.js
import Context from './context'
class Provider extends Component {
render(
return(
<Context.Provider value={{...this.props.context}}>
{this.props.render}
</Context.Provider>
)
)
}
ProductPage.js
import Context from './context'
class ProductPage extends Component {
render(
return(
<Context.Consumer>
{(context) => (
<p>{context.foo}</p>
)}
</Context.Consumer>
)
)
}
This way anything inside Provider should be able to access context without passing props around.
@johnmailey Will this work right now?
@i2chris I can see it's being used in the wild so I'd say so.
I have moved away from react_rails and i cant remember why I put this here but looking back it looks like something that would work. @i2chris.
We have had no updates on this since 2019. Closing the issue.