I successfully passed an array of objects to the "value" attribute of a <li> element, and then connected that array to the component's state. However, for some reason, the array is

I need to render specific data based on the value attribute assigned in the li tag, which is stored in a state called otherState in my implementation

const [otherDetails, setOtherDetails] = React.useState([]);

const state = {
  listitems: [
    {
      id: 1,
      vendorContact: "User 1",
      otherDetails: [
        {
          firstName: 'U',
          lastName: 'I',
          city: 'O',
          zip: '560084'
        }
      ]
    },
    {
      id: 2,
      vendorContact: "User 2",
      otherDetails: [
        {
          firstName: 'D',
          lastName: 'N',
          city: 'W',
          zip: '560084'
        }
      ]
    },
    {
      id: 3,
      vendorContact: "User 3",
      otherDetails: [
        {
          firstName: 'A',
          lastName: 'B',
          city: 'V',
          zip: '560084'
        }
      ]
    }
  ]
};

I am using the value attribute of the li tag to display the data in a list:

<ul className="sidenavList">
  {state.listitems.map(listitem => (
    <li key={listitem.id} className="row" value={listitem.otherDetails} onClick={handleSelection}>
      {listitem.vendorContact}
    </li>
  ))}
</ul>

This is the part of the code where I am actually rendering the data using React:

<div className="right"> {
  <span>{otherDetails}</span>
  }
</div>

Updating the state on event

 const handleSelection = (e) => {
e.preventDefault();
setOtherDetails(e.target.getAttribute('value'))

}

Answer №1

Although I may not be able to address all your specific requirements outlined in your comment, I have developed a simple implementation that assigns a unique id to each element. This enables the click handler to efficiently retrieve the necessary item and update the state accordingly. It's important to consider how the state variable should be managed – whether it should be passed as a prop or handled as a distinct useState element.

const App = () => {
  const [selectedDetails, setSelectedDetails] = React.useState([]);

  const state = { items: [{ id: 1, name: "Item 1", details: [{ attribute1: 'Value 1', attribute2: 'Value 2' }] }, { id: 2, name: "Item 2", details: [{ attribute1: 'Value 3', attribute2: 'Value 4' }] }, { id: 3, name: "Item 3", details: [{ attribute1: 'Value 5', attribute2: 'Value 6' }] }] };

  const handleSelect = (e) => {
    const selectedItem = state.items.find(({ id }) => id == e.target.id)
    setSelectedDetails(selectedItem.details)
  }

  return (
    <div>
      <ul className="itemList">
        {state.items.map(item => (
          <li key={item.id} id={item.id} className="row" onClick={handleSelect}>
            {item.name}
          </li>
        ))}
      </ul>
      {selectedDetails.length ?
        <div className="selectedDetails">
          {selectedDetails.map(detail => (
            Object.keys(detail).map(key => (
              <p>{key}<span> {detail[key]}</span></p>
            ))
          ))}
        </div>
        : null}
    </div>
  )
}

ReactDOM.render(
  <App />,
  document.getElementById("main")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>

<div id="main"></div>

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

What is the best way to assign three different dates in my protractor test?

I am facing an issue with setting random dates in 3 date fields in a row using Protractor. The problem is that Protractor sets the dates too quickly and sometimes assigns invalid dates like: first data: 01/08/1990 (correct) second data: 01/09/0009 (inva ...

Creating a hover state for a CSS class seems straightforward, but I'm finding it a bit tricky

I am looking to customize my inline menu by changing the last menu item to a different colored box with unique text. I have successfully applied a custom style using the #navbar a.blogbox class, but I am struggling to figure out how to change the hover s ...

Is there a way to retrieve the final elements from a deeply nested array?

I've been struggling to extract the last item from a nested array of objects. I've tried using methods like flatMap, flat, filter, and splice, but so far haven't had any luck getting the desired array. const array = [ [ { total_c ...

What is the best way to detect the presence of the special characters "<" or ">" in a user input using JavaScript?

Looking to identify the presence of < or > in user input using JavaScript. Anyone have a suggestion for the regular expression to use? The current regex is not functioning as expected. var spclChar=/^[<>]$/; if(searchCriteria.firstNa ...

Tips for designing a table with a stationary first column in HTML/CSS

I am looking to design a table that can be horizontally scrolled with a dynamic number of columns. The goal is to keep the first column fixed/frozen while scrolling horizontally. I attempted to achieve this using the following CSS, which successfully keeps ...

Creating a Fixed Footer with CSS

Another question on the same topic, with a twist. Despite trying various solutions found in countless articles, none seem to work for me. My familiarity with HTML/CSS is limited due to just a few months of off-and-on practice. Hence, I'm seeking help ...

The issue of the tooltip or title not showing for cell with more than 2000 characters in jqgrid

I've been attempting to implement a tooltip or title with 2000 characters for a cell within a table that contains an image. I've tried various approaches but haven't been successful in finding a solution. Can someone please assist me? Here i ...

Place an element in a higher position than a slideshow

I recently encountered an issue where I was trying to place a png image above my slideshow. Despite trying various solutions, the image always appeared behind or on top without transparency. Based on the erratic display, it seems like the problem might be ...

What is the best way to retrieve an element that has been altered in its state?

I encountered a scenario where I want an image to have a border when clicked, and if clicked again, the border should be removed. However, the border should also be removed if another image is clicked instead. I believe there are a couple of approaches to ...

The TS-Mocha and Chai duo have encountered a hitch: a peculiar error message, TS2695, informing them that the left side of the

Software Versions: "ts-mocha": "^8.0.0", "ts-node": "^10.3.0", "chai": "^4.3.4", Sample Code: expect(wrapper.find(MyListItem)).to.have.length(3); Execution Command: ts-mocha tests/**/*.tsx -r u ...

Utilizing conditional statements in React js to showcase a distinct component

I am looking to create a function or conditional statement that dynamically displays different components based on whether the user has purchased products. If the user has bought products, I want to display the product components; if not, I would like to s ...

Issues with displaying images in React when using inline styles and an external JavaScript object are hindering the

Recently, I started diving into the world of React and have been following video tutorials to grasp the concepts. However, I've hit a roadblock on my project. I am building a real estate listing site using React, and the search results are populated f ...

Issue with React hook state persistence in recursive function

I implemented a recursion custom hook that utilizes a setTimeout function to provide 3 chances for an operation. Once the chances run out, the recursion should stop. However, I encountered an issue where the setTimeout function is not properly decrementin ...

Replacing data in a Node server

I am currently working on a server that temporarily stores files in its memory before uploading them to the database. Below is the code snippet I'm using: uploadImage(file, uid, res) { var fs = require('fs'); mongoose.connect(config ...

Error occurs after upgrading React app to vite due to node-fetch issue

I'm a bit perplexed by this issue. Transitioning the build tool to vite has been seamless except for encountering this error: No matching export in "node_modules/node-fetch/lib/index.mjs" for import "RequestInit" No matching expor ...

Show me a way to use jQuery to show the number of images of a particular type that are on a

My webpage features 6 different images, including 4 of various balls such as basketball and baseball. One image is of a truck, while the last one is random. On the page, there is a form with two radio buttons allowing users to select which type of image c ...

What is the best way to convert an Angular object into a string using a for-loop and display it using $sce in AngularJS?

Currently, I am rendering a block of HTML and directives using $sce.trustAsHtml. To achieve this, I utilized a directive called compile-template which enables the use of ng-directives like ng-click and ng-disabled. While it is possible for me to pass sta ...

What is the best way to add custom styles to Material UI tabs in a React application?

I need help styling my material UI tabs within a react component. I am having trouble getting the styles applied correctly, specifically setting the background color and box shadow of the entire bar, as well as defining the indicator background color and u ...

Learn how to easily alter the background color of a div in real-time by utilizing a color picker or color swatches feature in your

Would it be feasible to dynamically alter the background color of the .hasPicked class? I am interested in adjusting the background color using an input color picker and color swatches. I have already included the necessary code on Codepen. Check it out h ...

The CSS files undergo modifications when executing the command "npm run dev"

I've been working on an open-source project where I encountered a bug. Even when there are no images to display, the "Load More" button in the web browser extension still appears. To fix this, I decided to add the class `removeButton` to the button an ...