shakacode / react_on_rails

Integration of React + Webpack + Rails + rails/webpacker including server-side rendering of React, enabling a better developer experience and faster client performance.
https://www.shakacode.com/react-on-rails/docs/
MIT License
5.12k stars 630 forks source link

Add support for passing `children` in from Rails #1650

Closed rangerscience closed 1 month ago

rangerscience commented 2 months ago

Summary

Allows you to do: (rails template)

<%= react_component "MyComponent" do %>
  <%= render "events/form", event: Event.new %>
<% end %>

(react component)

const MyComponent= () => {
    return (
    <div>
      { props.children }
    </div>
  )
}

Note that this uses React's dangerouslySetInnerHtml, which... maybe isn't a good idea, but might be fine, since the HTML being set is coming in from the Rails template engine.

You could just include the changes to the Ruby code so that the block gets rendered, and that gets passed in a a nice prop (like children_html) but then the React components would have to care about whether their children are coming in from more React code, or from the Rails side of things.

Pull Request checklist

Remove this line after checking all the items here. If the item is not applicable to the PR, both check it out and wrap it by ~.

Other Information

As per the contribution guidelines, I'm supposed to run rake examples:gen_all, but that task doesn't exist


This change is Reviewable

Summary by CodeRabbit

coderabbitai[bot] commented 2 months ago

Walkthrough

The changes enhance the react_component and react_component_hash methods in the ReactOnRails::Helper module to accept block parameters, allowing for the inclusion of child HTML elements. The internal logic for rendering remains largely unchanged, but the handling of props has been improved. Documentation updates clarify the new functionality and provide guidance on using render-functions and security considerations with dangerouslySetInnerHtml.

Changes

Files Change Summary
lib/react_on_rails/helper.rb The react_component and react_component_hash methods now accept a block for child elements, initializing options[:props] with an empty hash if not provided.
Documentation Updated to include new functionality for passing blocks to react_component, clarifying render-functions, and addressing security concerns with dangerouslySetInnerHtml.

Poem

In the garden of code where rabbits play,
New features bloom, brightening the day.
With blocks of joy, we nestle and weave,
React components dance, oh, how they believe!
Hopping through changes, we cheer and we sing,
For every new line, a fresh spring! 🐰✨


πŸ“œ Recent review details **Configuration used: CodeRabbit UI** **Review profile: CHILL**
πŸ“₯ Commits Files that changed from the base of the PR and between 0caeb6e547aa0e3e040731db0cf58c44de4eb324 and eceb9f488c4ceb1ed0ed8145e62c69dcb432db53.
πŸ“’ Files selected for processing (1) * lib/react_on_rails/helper.rb (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1) * lib/react_on_rails/helper.rb
--- Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?
❀️ Share - [X](https://twitter.com/intent/tweet?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A&url=https%3A//coderabbit.ai) - [Mastodon](https://mastodon.social/share?text=I%20just%20used%20%40coderabbitai%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20the%20proprietary%20code.%20Check%20it%20out%3A%20https%3A%2F%2Fcoderabbit.ai) - [Reddit](https://www.reddit.com/submit?title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&text=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code.%20Check%20it%20out%3A%20https%3A//coderabbit.ai) - [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fcoderabbit.ai&mini=true&title=Great%20tool%20for%20code%20review%20-%20CodeRabbit&summary=I%20just%20used%20CodeRabbit%20for%20my%20code%20review%2C%20and%20it%27s%20fantastic%21%20It%27s%20free%20for%20OSS%20and%20offers%20a%20free%20trial%20for%20proprietary%20code)
πŸͺ§ Tips ### Chat There are 3 ways to chat with [CodeRabbit](https://coderabbit.ai): - Review comments: Directly reply to a review comment made by CodeRabbit. Example: - `I pushed a fix in commit , please review it.` - `Generate unit testing code for this file.` - `Open a follow-up GitHub issue for this discussion.` - Files and specific lines of code (under the "Files changed" tab): Tag `@coderabbitai` in a new review comment at the desired location with your query. Examples: - `@coderabbitai generate unit testing code for this file.` - `@coderabbitai modularize this function.` - PR comments: Tag `@coderabbitai` in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples: - `@coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.` - `@coderabbitai read src/utils.ts and generate unit testing code.` - `@coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.` - `@coderabbitai help me debug CodeRabbit configuration file.` Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. ### CodeRabbit Commands (Invoked using PR comments) - `@coderabbitai pause` to pause the reviews on a PR. - `@coderabbitai resume` to resume the paused reviews. - `@coderabbitai review` to trigger an incremental review. This is useful when automatic reviews are disabled for the repository. - `@coderabbitai full review` to do a full review from scratch and review all the files again. - `@coderabbitai summary` to regenerate the summary of the PR. - `@coderabbitai resolve` resolve all the CodeRabbit review comments. - `@coderabbitai configuration` to show the current CodeRabbit configuration for the repository. - `@coderabbitai help` to get help. ### Other keywords and placeholders - Add `@coderabbitai ignore` anywhere in the PR description to prevent this PR from being reviewed. - Add `@coderabbitai summary` to generate the high-level summary at a specific location in the PR description. - Add `@coderabbitai` anywhere in the PR title to generate the title automatically. ### CodeRabbit Configuration File (`.coderabbit.yaml`) - You can programmatically configure CodeRabbit by adding a `.coderabbit.yaml` file to the root of your repository. - Please see the [configuration documentation](https://docs.coderabbit.ai/guides/configure-coderabbit) for more information. - If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: `# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json` ### Documentation and Community - Visit our [Documentation](https://coderabbit.ai/docs) for detailed information on how to use CodeRabbit. - Join our [Discord Community](http://discord.gg/coderabbit) to get help, request features, and share feedback. - Follow us on [X/Twitter](https://twitter.com/coderabbitai) for updates and announcements.
justin808 commented 2 months ago

@rangerscience Why not just pass the HTML as a prop and let the react component handle the HTML?

rangerscience commented 2 months ago

@rangerscience Why not just pass the HTML as a prop and let the react component handle the HTML?

Sure! So, then, if you want to have a React component that can take children when used from both Rails and other React components -

# Rails
<%= react_component "MyComponent" do %>
  <%= render "events/form", event: Event.new %>
<% end %>
// React
const ParentComponent = () => {
  return <div>
    <MyComponent>
      <div>Children!</div>
    </MyComponent>
  </div>
}

You'd need to do:

const MyComponent= () => {
    return (
    <div>
      { props.children }
      { props.children_html && <div dangerouslySetInnerHtml={{__html: props.children_html}} /> }
    </div>
  )
}

By having React on Rails turn the passed HTML into a React element, the React components don't have to "know" whether they're being invoked by the Rails layer or by the React layer - they get to act just like regular React components.

justin808 commented 2 months ago

Given an easy work around, why expand the API?

rangerscience commented 2 months ago

Given an easy work around, why expand the API?

Sure! IMHO, developer happiness, least-surprise, and laziness. You can workaround both changes:

<%= react_component "MyComponent", props: { children_html: render_to_string("events/form") } %>
const MyComponent = () => <div>{ props.children_html && <div dangerouslySetInnerHtml={{__html: props.children_html}} /> } />

but this makes the developer's intention less clear (all we're doing is passing child elements, nothing more), requires boilerplate, and breaks expectations (causing surprise) - Rails templates can take blocks (presuming the template has a yield); React components can take children (presuming they put { children } somewhere). Without these changes, neither is true for React on Rails components.

This API expansion allows both the Rails and React side of things to work as intuitively expected and in-line with the rest of their ecosystems. It's also a pretty minimal set of changes - four lines of code or so, depending on how you count? - so the maintenance cost should be minimal as well.

Those are some arguments for why this API expansion is worthwhile. If the debate is actually about the generalized debate over whether or not APIs should be expanded when workarounds are available, that's a different discussion that I'd be happy to have :)

justin808 commented 1 month ago

Closing for now as this is easily done via the current API. @rangerscience could you provide a doc PR instead?

rangerscience commented 1 month ago

No worries, I'll just keep my fork up and running :) I've got some other changes I want to look at, so if I write up docs it'll be there (and after that), and at that point I'll welcome and help out if y'all want to open a PR from me to you.

I would recommend adding a bit to the docs pointing to this PR, if you want a quick and easy way to get someone this info - or, otherwise make sure the GH PR search pulls this up with search terms you'd expect someone to use.

justin808 commented 1 month ago

I'm not sure if pointing the docs to the implementation of an added API that was not added will help.

Thanks in advance for docs on how to cleanly accomplish the goal with the existing API.