The onClick event listener is not being recognized when using ReactDOMServer.renderToString

I am attempting to replicate the functionality of this fiddle: http://jsfiddle.net/jhudson8/135oo6f8/

(I also tried this example http://codepen.io/adamaoc/pen/wBGGQv and encountered the same issue with the onClick handler)

My goal is to make the fiddle compatible with server-side rendering, utilizing ReactDOMServer.renderToString

Here is the call I have:

   res.send(ReactDOMServer.renderToString((
            <html>
            <head>

                <link href={'/styles/style-accordion.css'} rel={'stylesheet'} type={'text/css'}></link>

            </head>

            <body>


            <Accordion selected='2'>
                <AccordionSection title='Section 1' id='1'>
                    Section 1 content
                </AccordionSection>
                <AccordionSection title='Section 2' id='2'>
                    Section 2 content
                </AccordionSection>
                <AccordionSection title='Section 3' id='3'>
                    Section 3 content
                </AccordionSection>
            </Accordion>
            </body>
            </html>
        )));

The Accordion element code is as follows:

// Accordion component code here...

The AccordionSection component code looks like this:

// AccordionSection component code here...

Although everything seems to be functioning correctly and the CSS is applied, the issue lies in the fact that the onClick event does not trigger. Clicking on the accordion elements has no effect. Can anyone provide insight into why the onClick handler may not be registering in this scenario?

Answer №1

When using React DOM render to string, only the initial HTML is sent as a string without any JavaScript included.
In order to handle JS functionality on the client side, you also need a react router that will attach the necessary JS handlers based on their react-id's. This ensures that the JS code runs effectively on both sides.
For a quick start with universal rendering boilerplate, check out this link.
If you're looking for more information on similar topics, you may find this question helpful: React.js Serverside rendering and Event Handlers

Answer №2

When it comes to server-side rendering with hooks in React components, registering hooks with ReactDOMServer.RenderToString can be tricky. One workaround is to bundle the component on the client using tools like webpack or gulp, and then utilize ReactDOMServer.RenderToString on the server side.

If you're looking for more guidance on this topic, check out this helpful blog post:

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

Bootstrap 4 Nav Table of Contents with Expand and Collapse Feature

Currently, I am encountering an issue with implementing a button to expand and collapse a "table of contents" in Bootstrap 4. The code I have so far can be viewed here: https://codepen.io/nht910/pen/RwwwyKB Code Snippet: <div class="main-wrapper col- ...

Next.js Read function is failing to return the most recent data following create or delete actions

My latest project involves building a todo list application using the latest version of Next.js (v13) in the app directory. Utilizing the capabilities of Next.js, I have written both client and server-side code to facilitate the functionalities of creating ...

playing with JSON data in angular

Currently, I am utilizing AngularJS and making use of $http.get to fetch a JSON response which I then assign to $scope.myObjects. After implementing ng-repeat="object in myObjects" in the HTML, everything seems to be functioning properly. My query pertai ...

Instruct npm to search for node_modules in an alternate directory

npm searches for node_modules in the current directory, as well as its parent directories before checking the global location. The proposed directory structure I am currently considering is as follows: global package.json node_modules/ project-1 gulpf ...

Navigate to a different web page within the body tag without changing the current URL by utilizing a hash symbol

I am working with two HTML files, index.html and about.html. My goal is to display the content of about.html within my index.html without navigating away from it. After observing many websites, I noticed that they often use #about in their URLs to dynamic ...

Encountered 'Exceeded Maximum Call Stack Size' error with dotenv-expand while running React on CircleCI

I'm currently facing an error while attempting to build a react app on CircleCI. This issue has recently surfaced whenever I run the command npm run build in my circle.yml file: #!/bin/bash -eo pipefail npm run build > <a href="/cdn-cgi/l/ ...

Ways to change the CSS styles of components within App

When my app is in full screen mode, I need to increase the font size for certain components. Within my App.jsx file, I have a variable that adds the "fullscreen" class to the root DIV of the app when triggered. Instead of using a blanket approach like * ...

What causes a block element to not stretch to match the width of its parent when it is in a fixed position?

I am currently developing a fixed horizontal navigation bar that spans the entire width of the screen. However, when I attempt to make its position fixed, the unordered list element only occupies the width required to contain its content. Considering that ...

Choosing an HTML element within a useEffect Hook

Having an issue with selecting an element inside another element in the DOM that was selected using the useRef hook. const editorRef = useRef(null); Trying to access the child element on the editorRef within a useEffect hook. useEffect(() => { edito ...

My postman is successfully uploading image files, but for some reason, my code isn't cooperating. Are there any adjustments that need to be made?

While attempting to upload an image file with form data in Angular, I encountered a discrepancy in behavior between Postman and my project. In Postman, under the headers section, I have configured the following: Content-Type: multipart/form-data, token: ...

Showcasing a graphical representation with the help of Highcharts

I am currently exploring JavaScript and trying to familiarize myself with interactive charts using the HighCharts library. Unfortunately, I have been facing some challenges in getting the graph to print correctly. Despite attempting various examples, none ...

How can I pass a variable name as an argument in Vue?

I am exploring ways to create a method that can efficiently load and assign JSON files to dynamic variables. Despite my efforts, varA and varB are not being populated as expected: data() { return { varA: Array, varB: Array } }, ...

Header Text unexpectedly breaking out of Div in Mozilla Firefox, but not in Chrome or IE

Need some help with getting the h5 text to show up inside the div with id="text". Any advice would be appreciated! Thanks for taking the time to read this! <div id="footer"> <div id="instagram"> <div id="text"> &l ...

What is the best way to retrieve route data based on route name in VueJs?

When working with VueJs, I have found that I can easily access the data of the current route. However, I have encountered a situation where I need to access the data of a different route by its name. Let's say I have defined the following routes: [ ...

Obtain resources from the NPM repository

I recently encountered an issue while trying to utilize font-awesome with npm. The newest version (>4) made it challenging to locate the fonts directory. Previously, I used a npm script similar to cp -R ./node_modules/font-awesome/fonts/* dist/assets/. ...

Having trouble with React throwing a SyntaxError for an unexpected token?

Error message: Syntax error: D:/file/repo/webpage/react_demo/src/App.js: Unexpected token (34:5) 32 | 33 | return ( > 34 <> | ^ 35 <div className="status">{status}</div> 36 <div className=&quo ...

displaying date picker on button click with angular bootstrap ui

I am trying to display an AngularJS Bootstrap calendar only upon clicking a button, and I want to restrict it from appearing when clicking on the input field. Below is my code: <input type="text" onkeydown="return false;" ...

Adjusting the size of DIVs according to images retrieved dynamically from a database

I am currently in the process of building my online portfolio, and while I am new to JQuery and PHP, I am working through any challenges that come my way. However, I am facing a roadblock that has left me puzzled. My goal is to create a seamless iframe to ...

Transformation of data structures

Is there a way to transform the array structure that represents parent-relation into a 2D array format? const array = [{id: 1, parentId: 2}, {parentId: null, id: 2}]; The goal is to create a new array where the first element of each nested array is the pa ...

What are some effective methods for handling error objects in REST API services?

Encountered an error object: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: YES) Type of (err): Object Now, I am looking to pass this object to another web service (REST API) What content ty ...