Several buttons dysfunctional when in a div that is initially hidden

Currently, I am in the process of constructing a custom WordPress block using React on the frontend. The primary function of this block is to fetch and display a list from a server utilizing the map method. Each item in the list features a header that, when clicked, reveals its content. To achieve this effect, the content sections are initially hidden with max-height and opacity properties set to 0, allowing for smooth CSS transitions upon opening.

Nevertheless, I have encountered an issue where some of the content-divs within the list entries do not behave as expected. Specifically, links styled as buttons, such as music service links, fail to function properly despite having their href attributes correctly specified in the markup. Furthermore, hovering effects are also missing, resulting in an unclickable state.

Interestingly, this problem is inconsistent, affecting only certain list entries while leaving others unaffected. Strangely, opening a different section with working buttons seems to temporarily fix the malfunctioning buttons in previously affected entries. However, closing the functioning section, reverts the formerly fixed buttons back to their faulty state.

This perplexing behavior almost feels like my code is bewitched or haunted in some way.

It's worth noting that due to the dynamic nature of the list in terms of length and content, I resort to generating IDs and employing getElementByID queries for interaction rather than defining static states for each item.

In the React code snippet provided below:

//...
//releases is useState([]) containing song metadata objects
//returned from database query with known columns
{releases.map(release => {return(
  <div key={release.catalogue_index} style={{marginTop: "8px"}}>
    {/*Header content shown in the screenshot*/}
    <div className="layout-row" style={{backgroundColor: "#111", padding: "8px", marginTop: "4px", position: "relative"}} onClick={(event) => {
      document.getElementById(`${release.catalogue_index}-content`).classList.toggle('open');
      }}>
      <div stlye={{flexGrow: 1}} className="layout-stack">
        {/* Title and information displayed here */}
      </div>
    </div>

    {/*Content visible after clicking (second screenshot)*/}
    <div className="release-content" id={`${release.catalogue_index}-content`}>
      // ... Other content elements here
    </div>
  </div>
)})}

The CSS styling includes transitions for the .release-content class to toggle between hidden and visible states smoothly through changes in max-height and opacity.

The troubleshooting leads me to consider potential interference from WordPress classes ("wp-..."), however, this theory remains inconclusive as only specific list entries exhibit issues, while others perform flawlessly despite sharing these common classes.

Answer №1

After taking RubenSmn's advice, I came to the realization that my code structure was not well-planned and contained numerous anti-patterns. I decided to refactor the code by creating a separate component <Release />, rather than embedding all the markup directly.

{releases.map(release => {return(
  <ReleaseComponent key={release.catalogue_index} release={release} />
)})}

The new component no longer uses classList.toggle, but utilizes React states to manage the visibility of content panels. Additionally, instead of using document.getElementByID queries, I incorporated proper React refs.

const ReleaseComponent = (props) => {
  const contentDiv = useRef(null);
  const audioElement = useRef(null);
  const audioButton = useRef(null);
  const audioSeek = useRef(null);

  const [contentOpen, setContentOpen] = useState(false);
  //...
  return(
    //...
    <div className="release-content" ref={contentDiv} hidden={!contentOpen}>

  //...

It turns out that when you follow best practices, things actually work as intended... This experience has been quite humbling. Grateful for the guidance, @RubenSmn.

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

Troubleshooting Authentication Problems with Next.js and Kinde

'use client' const { useState } = require('react'); const Link = require('next/link'); const Image = require('next/image'); const { RegisterLink, LoginLink, LogoutLink } = require('@kinde-oss/kinde-auth-nextjs/ ...

The message "Temporary headers are displayed" appears in Chrome

After creating an API to remove images from a MongoDB database using GridFS, I encountered an issue when calling the API. The image is successfully removed, but it causes the server to stop with an error that only occurs in Chrome, displaying "Provisional ...

Persist the current scroll position of a div in local storage using React

Despite the numerous questions I've come across on this topic, none of them align with my approach. Most solutions involve window scrolling, but I have a div containing overflow items that I want to retain the user's scroll position for. My attem ...

Disconnect event happening

I am currently studying nodejs using a French tutorial on creating a chat application with nodejs https://www.youtube.com/watch?v=8jkkd2Ohte8 However, I am facing an issue when trying to track the users who leave the chat room. This is my Server.js code: ...

Encountering unidentified data leading to the error message "Query data must be defined"

Currently, I'm utilizing Next.js to develop a project for my portfolio. In order to manage the API, I decided to implement both Tanstack query and Axios. The issue arises when attempting to retrieve the data as an error surfaces. Oddly enough, while ...

Trigger the onclick method by selecting an icon within the MUI DataGrid

Currently, I am utilizing the default MUI Dialog model in the "DialogModel.js" component. Additionally, I have integrated another MUI DataGrid component as shown below: // RulesTable.js import * as React from 'react'; import { DataGrid } from &a ...

"Internet Explorer text input detecting a keyboard event triggered by the user typing in a

It appears that the onkeyup event is not triggered in IE8/IE9 (uncertain about 10) when the enter button is pressed in an input box, if a button element is present on the page. <html> <head> <script> function onku(id, e) { var keyC = ...

Using jQuery to send single value arrays through AJAX requests

I've come across numerous discussions regarding how to send arrays via ajax in jquery. However, my query is slightly different. I am unsure if what I am seeing is normal behavior or if there is an error in my approach. Here is a simple jquery snippet ...

Modifying an element within a nested array

I am struggling to create a JavaScript function that can update the "checked" value within an object in an array structured as follows: array:[ { id:1, name:"foo", options: [ {id:"one", checked: false}, {id:"two", checked: true} ] ...

How can you ensure that the Data Point Values are always displayed when using arrayToDataTable in the Google Charts API?

Just wanted to clarify that even though there is a similar question titled: Google Charts API: Always show the Data Point Values in Graph ...on this website, I am facing difficulties implementing its solution because my chart is using arrayToDataTable. ...

Tips for successfully changing the styling using CSS that was previously altered with JavaScript

I have already gone through this question but couldn't find a solution. I used JavaScript to apply the style to the element with the id "left-container" instead of using a class, and now I'm unable to override it! You can view the demo for a m ...

Mistakes related to using FBXLoader in Three.js

I recently delved into the world of three.js and decided to follow a helpful tutorial on loading GLTF Models using Three.js. Excited to further my skills, I wanted to experiment by utilizing the FBX loader to import and animate models from Mixamo. The tut ...

Tips for retrieving page source with selenium Remote Control

Looking to Develop a Basic Java Web Crawler. WebDriver driver = new HtmlUnitDriver(); driver.get("https://examplewebsite.com"); String pageSource=driver.getPageSource(); System.out.println(pageSource); The result is as follows: <!DOCTYPE html PUBLIC ...

JavaScript returns the value 'undefined' when a function variable is used with an array of objects

Here is an example of an array of objects: var theArray = [ {theId:'1', num: 34}, {theId:'2', num: 23}, {theId:'5', num: 26} ]; This function successfully loops through the array: function printValues() { va ...

The value of Yargs.argv is consistently displayed as [object Object]

In my Ubuntu 16.04 environment, I enrolled in a node.js course on Udemy. Following the instructor's guidance, I initially used the exact version mentioned and later updated to the latest version (11.0.0). Surprisingly, both versions yielded the same o ...

Conflicting React Dependency Version 18.0 and Material-UI: A Compatibility Issue

I have attempted all the suggestions provided here, but unfortunately, none of them seem to work. I am encountering an issue with Material UI Icons npm installation which is causing me to be unable to resolve the dependency tree. Additionally, I am also fa ...

Adding an item to a pre-existing entity (using Many-to-One and One-to-Many relationships)

I've been grappling with a challenge for two days now, trying to find a solution through tutorials and readings without success. The issue revolves around two classes: Building and Group. Each building is associated with one group, while a group can p ...

Having trouble replacing scss variables in react-h5-audio-player

I recently integrated react-h5-audio-player into my project and followed the instructions on the README page to customize the styles by updating the SCSS variables that control the colors. However, it appears that my custom styles are not being applied. An ...

Unpacking Functions within Embedded Redux Reducer

My current challenge involves dispatching an action that has the following structure: { type: "TOGGLE_FARA", fara: true, id: "5d20d019cf42731c8f706db1" } The purpose of this action is to modify the "enabled" property within my "fara" state. The configura ...

Is it possible for two-way binding to function in index.html within Angular 4?

Does two-way binding function in index.html? I have some links and metadata in index.html. How can we define head parameters in a component? <head> <meta name="og:title" content={{titleValue}}> <meta name="og:url" content={{urlValue}}> & ...