Is there a way to trigger the document.addEventListener 'turbolinks:load' function when transitioning from a link_to helper using React Webpacker in Rails 5?

I am currently working on a project using React with Webpacker on Rails 5. When I navigate to the page using the link_to helper, it seems like the JavaScript under

document.addEventListener('turbolinks:load')
is not functioning properly.

The main controller for this project is called insurance_form_container.jsx

import React from 'react'
import ReactDOM from 'react-dom'
import StartForm from './insurance_form/start_form'

console.log('root react')

document.addEventListener('turbolinks:load',function () {
  ReactDOM.render(
    <StartForm />,
    document.getElementById('start-form-index-container')
  )
})

This is the HTML template for the specified route

<div class="container">
  <div id="start-form-index-container">

  </div>
</div>

<%= content_for(:footer) do %>
    <%= javascript_pack_tag('insurance_form_container') %>
<% end %>

This is the link from another page.

<%= link_to users_insurance_form_start_path,
            class: 'btn btn-lg btn-success btn-primary-green' do %>
    Proceed
<% end %>

It appears that console.log('root react') is executing correctly, but ReactDOM.render is not running at all unless the page is refreshed. Am I overlooking something? How can I ensure that the `.jsx` code runs smoothly through the `link_to` helper?

Thank you!

Answer №1

It seems like the code is following your instructions correctly. The Event Listener is added after the turbolinks:load event, meaning it will only run when you navigate to a new page and trigger the first turbolinks:load event after adding the listener.

If you want the code to execute on page load rather than waiting for another navigation event, consider using an event trigger like document.on("turbolinks:load").

document.on("turbolinks:load", function() {
  ReactDOM.render(
   <StartForm />,
   document.getElementById('start-form-index-container')
  )
});

Answer №2

Hi, I also experienced this issue in the past.

In my case, I had bundled my react code in the header section along with other stimulus code. However, this approach was too early for adding document event listeners.

After separating the react code from the main bundle and loading it into the footer of the website, I was able to successfully implement the following solution:

import * as React from 'react'
import ReactDOM from 'react-dom/client'
import App from "./App"

const initializeReactPage = () => {
    const element = document.getElementById('js-robot-ui')
    if(element) {
        const root = ReactDOM.createRoot(element)
        const config = JSON.parse(element.dataset.config)
        root.render(<App config={config}/>)
    }
}

document.addEventListener("turbolinks:load", initializeReactPage)
initializeReactPage()

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Could you please include some additional information in the provided prompt

Automating the Window: https://i.sstatic.net/CEKpH.png Issue: Our team recently implemented an authentication process for our staging environment, which requires additional steps during testing. I discovered that 'prompt()' cannot be easily capt ...

Observing ng-model within various nested ng-repeat loops

Here is a snippet of code that I am struggling with: <div ng-repeat="category in categories"> <div ng-repeat="(key, value) in category"> {{ key + ":"}} <select id={{key}} class="my_select" ...

Having trouble adding elements (after the initial iteration) using the push() method in JavaScript

I'm facing an issue where I have a string and an array, but I'm unable to push elements after the first iteration. Below is the code I'm using: response1 = "hello"; var arr = [""]; arr.push(response1); console.log("First position " + arr[0 ...

In the realm of React Native, an error arises when attempting to access 'this._nativeModule.isBluetoothEnabled', as the reference to null prevents it from

Recently, I delved into working with react native and attempted to incorporate react-native-bluetooth-classic into my project. The URL for the API overview can be found here. However, I encountered an issue that has me stuck: "TypeError: null is not ...

Dealing with Challenges in Constructing JQuery URLs

I'm facing an issue with loading a website into a specific div (div.content). The website I'm trying to load requires a login through a POST request. When the javascript attempts to load the site, it recognizes the redirection to the login form ...

How can jQuery be used to transmit boolean field data from a template to Django views?

Is there a way to use jQuery to send form values from a template to a database? I am looking to change the boolean value in a checkbox and save it in a model, then send this information to the view using jQuery. Within my template, I have the following co ...

Comparing Inline SVG to CSS Background Sprite

As I work on developing multiple pages for my app (currently utilizing Angular on the front-end), I find myself including numerous logos. In an effort to maintain code readability, I have begun creating directives for each SVG logo by embedding the inline ...

Which characters should be encoded in an onclick event containing a string?

I'm having trouble figuring out which characters to escape in my string. My PHP code provides the string parameter, but it sometimes contains quotes and double quotes that I'm unsure how to handle. onclick="eventBox('This is the string &apo ...

Leveraging the AngularJS promise/defer feature alongside the Quickblox framework, learn how to efficiently upload images and subsequently upload public URLs to a custom

I am currently developing an application that requires users to upload 5 images of themselves. Using a backend-as-a-service platform like Quickblox, I have to create and upload blob files individually. Once each image is uploaded, I receive a success call ...

Having trouble interacting with the "Continue" button on PayPal while using Selenium

Recently, I have encountered an issue with automating payments via PayPal Sandbox. Everything used to work smoothly, but now I am unable to click the final Continue button no matter what method I try. I have attempted regular clicks, using the Actions cl ...

Using a Javascript method to access a sibling property within an object

Is there a way to access a sibling property from a method in JavaScript? This seemingly simple task has proven challenging for me. Take a look at the sample code below. let f = { a: 3, printMyBrother() { console.log(X) } }.printMyBrother f() ...

A regular expression in JavaScript for matching unpredictable numbers without any specific words preceding them

For instance, I am looking to extract the numbers that do not have 'the', 'abc', or 'he' before them; the89 (no match) thisis90 (match 90) iknow89999 (match 89999) getthe984754 (no match) abc58934(no match ...

Having trouble with the Semantic UI popup not showing div content correctly? Need to display table row data as well? Let's troub

Having trouble with this semantic-ui code popup error. Can anyone provide a solution? $(document).on('click', 'table td', function() { $(this) .popup({ popup: $('.custom.popup') }); }) ...

Loading an image into a Three.js scene

Attempting to display an image in my 360-degree scene, but encountering issues with the code: <script> var controls, camera, scene, renderer, element; var container; var sceneCube; init(); animate(); function init() { // CAMERAS camera ...

What could be causing setInterval to only run once?

setInterval is only running once for me. I tried using setTimeout and creating a loop inside the function, but it's still giving the same output. I'm working with brackets and using live preview, in case that matters. const buttons = document. ...

Encountered a snag while executing Powershell with Selenium: Error message - unable to interact with

Looking to update a textarea with a value? The script below triggers an error stating "element not interactable". This occurs because the textarea is set to "display:none". However, manually removing the "NONE" word allows the script to successfully set th ...

Is JavaScript necessary for this task in PHP?

Hi everyone, I recently discovered a way to style a PHP echo in a more visually appealing manner. Instead of presenting an unattractive colored box right away, I was wondering if there is a way to only display the box when the user selects the calculation ...

Programmatically trigger a click event on a specific list item

How can I make a li tag click automatically when my page loads? HTML: <div id="listDiv"> <ul id="listUL" class="listUL"> <li id="f1" class="listDynamic">Term1</li> <li id="f2" class="listDynamic">Term2& ...

Error occurs while making a request to the Google API using $.ajax

I am currently developing an angular application that includes a section for public transportation. I am trying to integrate directions from the Google API, and while the URL seems valid - returning JSON when entered in a browser - I encounter an error whe ...

Rotating a non-centered triangle geometry in ThreeJS

I've been struggling to understand why my triangle isn't rotating around the center as I expected. My goal is to have two triangles side by side, with one rotated 60 degrees. However, when I rotate them, all corners should remain the same size. ...