Retrieve a particular HTML element from an object that has been mapped

After reproducing my issue on a smaller scale for easier handling, I am now aiming to implement an onclick function that reveals the hidden content inside each column. The plan is to initially hide the content using display: none and then switch it to display: flex upon clicking. Due to the shared classname among all mapped components, I need to utilize an object like lodash instead of using document.getElement. Since the data originates from a database and varies based on user requirements, the number of columns is dynamic and unknown.

I'm seeking guidance on how to target the specific classname of the div or tag within the map iteration where the onclick event occurs. Any assistance would be greatly appreciated!

import _ from "lodash"
import React from 'react'

const dummyData = {
    columnOne: "item one",
    columnTwo: "item two",
    columnThree: "item three"
}

function TestPage() {
    return (
        _.map(dummyData, (data, key) => {
            return (
                <>
                    <div className="column-container">
                        <p className="heading">{key}</p>
                        <div className="show-content-btn">V</div> //button to toggle content visibility
                    </div>
                    <p className="content">{data}</p> //content to be hidden/shown
                </>
            )
        }

        )
    )
}


export default TestPage

Answer №1

One method is to utilize the useState hook for storing and toggling class names through an onClick event that changes state via setState.

To explore this further, check out the following resource. It should provide the information you're seeking.

Answer №2

To improve efficiency, consider creating a separate component for the HTML returned from the map function and managing state within it. For example:

import _ from "lodash";
import React from "react";

const sampleData = {
  columnOne: "item one",
  columnTwo: "item two",
  columnThree: "item three"
};

function DisplayData({ id, data }) {
  const [show, setShow] = React.useState(false);
  return (
    <>
      <div className="column-container">
        <p className="heading">{id}</p>
        <div className="show-content-btn">
          <button onClick={() => setShow(!show)}>V</button>
        </div>
      </div>
      {show && <p className="content">{data}</p>}
    </>
  );
}
function MyPage() {
  return _.map(sampleData, (data, key) => {
    return <DisplayData key={key} id={key} data={data} />;
  });
}

export default MyPage;

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

The JavaScript-generated form element will not be included in the data submitted through the POST method

While it may appear that this question has been asked before, my specific inquiry seems to be unique as I have not found a similar answer in other threads. Therefore, I am initiating a new discussion. My issue revolves around a form which contains a link ...

How can you master the art of PHP templating like a pro?

Years ago, I started a small PHP website that has since grown into quite a mess. Despite having a separate template for the final HTML output, I still find myself handling a lot of HTML within the 'business logic' part of the code. My main issue ...

Achieve horizontal bar movement by utilizing google.visualization.DataTable in a left-to-right motion

I am exploring the possibility of reversing the direction of a chart(bar) using google.visualization.DataTable. In the current setup, the bar progresses from left to right, but I wish for it to move from right to left instead. Below is what I have attempte ...

Text aligned vertically within an element using the table-cell display attribute in the Chrome browser

Struggling to align text inside an element styled with display: table-cell? The issue arises when dealing with multiline text in a tab format. Achieving the correct vertical-align: middle; requires displaying it as a table-cell, which works well in most ca ...

The issue of overwritten callbacks is occurring due to the use of multiple .use() functions on the

Utilizing a module known as consign, I am able to conveniently include multiple modules from a directory all at once, eliminating the need for numerous require statements. In my code, I have set the mount path for each endpoint at the beginning of the rout ...

Update the iframe URL to direct the user to a new tab instead of opening a popup

I have created the following script, but I am facing a challenge as I realize that the URL I want to use opens in a new tab instead of just forwarding: <script> function readCookie(name) { var nameEQ = name + "="; var ca = document.cookie.sp ...

Is there a way to seamlessly share TypeScript types between my Node.js/Express server and Vite-React frontend during deployment?

I'm currently tackling a project that involves a Node.js/Express backend and a Vite-React frontend. My goal is to efficiently share TypeScript types between the two. How should I configure my project and build process to achieve this seamless type sha ...

Steer clear from using the implicit 'any' type while utilizing Object.keys in Typescript

I have a unique situation where I need to loop over an Object while maintaining their type without encountering the error "Element implicitly has an 'any' type because 'ContactList' has no index signature". Despite extensive discussion ...

Different from Window.Print()

I am looking to implement a print button that will trigger the printing of the entire webpage when clicked. I have been attempting to achieve this using Window.print() in JavaScript, but I encountered an issue where the link stops working if the print bu ...

Express application failing to display react component in react application

I am in the process of developing an MVC Express application using React and node.js. In my file structure, I have an index.html file located in the public folder, and an index.jsx file in the views folder. After starting my server and navigating to local ...

Tips for inserting a php variable into an html document

I am trying to figure out how to export a variable from a php file into an html file. The php file I'm working with is example.php and it contains the following code: <?php $array= ['one','two']; ?> The html file is named ...

Having trouble getting ASPJAX to function properly

I'm looking to create a demo showcasing the combination of ASP and AJAX. I came across some code snippets from http://www.aspjax.com that I've incorporated into my project. However, I'm having trouble displaying the expected text. Here is t ...

How can the first paragraph value of a div be found using jQuery in Next.js?

How can I retrieve the value of the first <p> tag within my div when a button inside the same div is clicked? Despite attempting to use $(this), it doesn't appear to be functioning as expected. Take a look at the code snippet below: <div cla ...

Unable to reach a variable within the class itself

I'm facing an issue with my MobX store. In my Store class, when I try to access this.user.permits.db, I get an error stating that this.user is undefined. I am confused as to why I can't access the @observable user. src/ui/store/store.js file: ...

What methods are available to adjust the header color on various pages?

I have a solution that works for one location, but I need to add red color to multiple locations. How can I achieve this? import { useRouter } from "next/router"; function Header() { const router = useRouter(); return ( <> & ...

What is the best way to divide a string into an array containing both linked and non-linked elements?

I'm struggling to find the right solution to my problem. I need to create a view that is enclosed in a clickable div. The content will consist of plain text mixed with clickable URLs - the issue arises when clicking on a link also triggers the method ...

Using Accordions in Jquery to dynamically adjust page height during ajax calls

I am currently using AJAX to call in a page and animate its height successfully. However, I have encountered an issue with an accordion-like function that is supposed to toggle the visibility of an element and adjust the height of the containing element ac ...

Tips for deactivating dates in the jquery datepicker that correspond to entries in a MySQL database

Is there a way to disable dates directly from a MySQL database in jQuery Datepicker? It seems tedious to constantly update dates in JavaScript, so I'm exploring the option of storing future disable dates in the MySQL database and displaying them in th ...

The ReactJS apolloClient is unable to locate the "client" within the context or as an option provided

I'm having trouble understanding why this problem is occurring, especially since it was working fine in another application of mine. I've been trying to figure it out for the past 3 days without any luck. I came across a potential solution on st ...

The error message "Unexpected node environment at this time" occurred unexpectedly

I am currently watching a tutorial on YouTube to enhance my knowledge of Node.js and Express. To enable the use of nodemon, I made modifications to my package.json file as shown below: package.json "scripts": { "start": "if [[ $NODE_ENV == 'p ...