rails / jsbundling-rails

Bundle and transpile JavaScript in Rails with esbuild, rollup.js, or Webpack.
MIT License
831 stars 144 forks source link

How can I use React? #132

Closed benlieb closed 1 year ago

benlieb commented 1 year ago

I'm using ESbuild and want to use React components (with JSX) but not in a SPA way. How can I do this?

It's not obvious...

justin808 commented 1 year ago

You might want to check out https://github.com/shakacode/react_on_rails or https://github.com/shakacode/shakapacker.

Using React is not in the scope of this gem.

@dhh you probably should close this issue.

benlieb commented 1 year ago

Fair enough. For the record/posterity, I solved it be creating my own react_component helper:

helper

  def react_component(component:, props: {})
    render_to_string partial: 'shared/react_component', locals: { component: component, props: props }
  end

partial

- props ||= {}
- component ||= nil # needs to be registered in on_load
- container_id = SecureRandom.uuid

%div{id: container_id}
  = render partial: 'shared/spinner', locals: {size: 2}

:javascript
  window.addEventListener('load', () => {
  })

  document.addEventListener("DOMContentLoaded", () => {
    const container = document.getElementById('#{container_id}') 
    const root = window.app.ReactDOM.createRoot(container)
    let Component = window.app.components["#{component}"]
    if(!Component) console.error(`Component #{component} not loaded`)
    const props = #{raw(props.to_json)}
    root.render(
      window.app.React.createElement(Component, props) //needs this or jsx (can't use jsx in view
    )
  })