Home > Software design >  target specific HTML element from an object that is mapped
target specific HTML element from an object that is mapped

Time:06-03

So I have replicated my issue on a smaller level so its easier to work with. The goal is to have an onclick function that shows the content inside the column which is hidden as default, this will ideally be handled through setting display: none and changing to display: flex. I have to use an object hence lodash. I cant use document.getElement because all mapped components share a common classname. The data comes from a database so the amount of columns is unknown and always changing per user requirements.

I guess im looking for a method to target to the classname of the div/tag of the iteration of the map where the onclick for that container is. Any help is 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

CodePudding user response:

You can use useState to store classnames and then toggle them with onClick function by changing state with setState.

See this answer. I think it contains what you want.

CodePudding user response:

One way of doing this is by making a separate component for HTML which return from map function and handle state in it. Like:

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

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

function Data({ 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 TestPage() {
  return _.map(dummyData, (data, key) => {
    return <Data key={key} id={key} data={data} />;
  });
}

export default TestPage;
  • Related