Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Component Rendering but not visible in Rails Application

As the title says, none of my react components are visible when I run rails server. I am using the gem react-rails. I know they're rendering because when inspecting the body tag of the page, it has <div data-react-class="Home" data-react-props="{}"></div>.

To test if it was my computer, I made another rails application, created a react component in my root with the exact same format, being

class Home extends React.Component {
  render() {
    return (
      <h1>Hello</h1>
    )
  }
}

and it showed up on screen. I have absolutely no errors in my console, so I have no idea what the problem is. The difference between the two rails apps(the visible and non visible) are that the broken one is using devise, bootstrap, and has more migrations/models/controllers. Also, I removed turbolinks in the broken one, but even adding it back in, it doesn't make a difference.

like image 885
Nico Avatar asked Nov 09 '22 07:11

Nico


1 Answers

I was facing the same problem. Using react-rails gem.

No console error, webpacker compiled successfully. Also helper was working good react_component('Home') cause I could see in the html

<div data-react-class="Home" data-react-props="{}"></div>

When installing the gem the following example was within:

// Run this example by adding <%= javascript_pack_tag 'hello_react' %> 
// to the head of your layout file,
// like app/views/layouts/application.html.erb. 

// All it does is render <div>Hello React</div> at the bottom
// of the page.

import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'

const Hello = props => (
  <div>Hello {props.name}!</div>
)

Hello.defaultProps = {
  name: 'David'
}

Hello.propTypes = {
  name: PropTypes.string
}

document.addEventListener('DOMContentLoaded', () => {
  ReactDOM.render(
    <Hello name="React" />,
    document.body.appendChild(document.createElement('div')),
  )
})

Which was working good.

But the component is rendered when DOMContentLoaded event triggers. So the component was rendered by the client.

Anyways, reading the documentation found prerender

prerender: true to render the component on the server.

So using =react_component("Home", {}, {prerender: true}) worked to me.

like image 153
oskrgg Avatar answered Nov 14 '22 21:11

oskrgg