Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React component not rendering when using react-rails gem

I followed the 'Getting started with webpacker' in react-rails but on running the rails server I dont see the hello world component there.

app/javascript/components/HelloWorld.js

import React from "react"
import PropTypes from "prop-types"
class HelloWorld extends React.Component {
  render () {
    return (
      <React.Fragment>
        Greeting: {this.props.greeting}
      </React.Fragment>
    );
  }
}

HelloWorld.propTypes = {
  greeting: PropTypes.string
};
export default HelloWorld

views/layout/application.html.erb

<!DOCTYPE html>
<html>
  <head>
    <title>MyApp</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>

views/home/index.html.erb

<!DOCTYPE html>
    <html>
        <body>
            <p>Heloo</p>
            <%= react_component("HelloWorld", { greeting: "Hello from react-rails." }) %>
        </body>
    </html>

app/javascript/packs/application.js

/* eslint no-console:0 */
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.
//
// To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate
// layout file, like app/views/layouts/application.html.erb


// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

console.log('Hello World from Webpacker')
// Support component names relative to this directory:
var componentRequireContext = require.context("components", true)
var ReactRailsUJS = require("react_ujs")
ReactRailsUJS.useContext(componentRequireContext)

This is what I get when I try to access the webpage react-rails webpage

EDIT: Adding prerender: true (server-side rendering) in view, it works perfectly

<%= react_component("HelloWorld", { greeting: "Hello from react-rails." }, prerender: true) %>

but why wont client side rendering work?

like image 913
Anto Joy Avatar asked Sep 06 '25 03:09

Anto Joy


1 Answers

try adding

 <%= javascript_pack_tag 'application' %>

in your index.html.erb

like image 56
Realizt30 Avatar answered Sep 07 '25 19:09

Realizt30