I am trying to implement React on a RoR project. I added a frontend folder in my project directory and created a component file index.jsx, but it's not showing the changes I applied to the Rails view with React when I tested it with Rails server. Here's what I have in my Rails view:
<main id="root"></main>
And in my React frontend folder I have an index.jsx with below code:
import React from "react";
import ReactDOM from "react-dom";
document.addEventListener("DOMContentLoaded", () => {
const root = document.getElementById("root");
ReactDOM.render(<h1>Welcome to my page</h1>, root);
});
Basically what I'm trying to do is simply add a h1 tag to the root element, but I only see an empty main tag with id root when I inspected the page.
Not sure if this helps but here's my webpack.config.js
const path = require("path");
module.exports = {
context: __dirname,
entry: "./frontend/index.jsx",
output: {
path: path.resolve(__dirname, "app", "assets", "javascripts"),
filename: "bundle.js",
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
query: {
presets: ["@babel/env", "@babel/react"],
},
},
},
],
},
devtool: "source-map",
resolve: {
extensions: [".js", ".jsx", "*"],
},
};
I tried to add something directly in my Rails view and it works just fine, so I think I can assume it's a frontend problem.
<main id="root">
<h1>Test Rails</h1>
</main>
This is my view code that loads html, basically the default code for any rails new project.
<!DOCTYPE html>
<html>
<head>
<title>Intro-Me</title>
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= stylesheet_link_tag 'application', media: 'all' %>
<%= javascript_pack_tag 'application' %>
</head>
<body>
<%= yield %>
</body>
</html>
Please let me know if any information is needed. I appreciate any help on this:)
I think I'll just answer my own question, and the issue is in my webpack.config.js
. I didn't realize the directories and files in app folder are different now. When I was using Rails 5.2.4 this
output: {
path: path.resolve(__dirname, "app", "assets", "javascripts"),
filename: "bundle.js",
},
would work, when I had the script tag in application.html.erb
as
<%= javascript_include_tag 'application' %>
, but now they change it to
<%= javascript_pack_tag 'application' %>
in new version, whose route is /app/javascript/packs so now the output in webpack.config.js should be
output: {
path: path.resolve(__dirname, "app", "javascript", "packs"),
filename: "application.js",
},
This solved my problem.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.