What is the best way to present sorted items on a user interface?

I have a unique Med interface containing properties like drugClass, dosage, and name. Using this interface, I created an array of drugs with different attributes. How can I filter this array by drugClass and then display the filtered data on a web page?

// in Medications.ts
export interface Med {
  dosage: number;
  name: string;
  drugClass: medForm;
  forDog: boolean;
  forCat: boolean;
}

export const medications: Med[] = [
  {
    dosage: 0.03,
    name: "Meloxicam",
    drugClass: "Oral",
    forDog: true,
    forCat: true,
  }, ....// more here

// in page.tsx
import { Med, medications } from "./Medications"; 

export default function Home() {
 const filteredOralData = medications.filter(
    (med) => med.drugClass === "Oral"
  );

return (
<div>
<ul className="list-group">
                {filteredOralData.map((item) => (
                  <li>{item //ERROR: Type 'Med' is not assignable to type 'ReactNode'.ts(2322)
index.d.ts(1450, 9): The expected type comes from property 'children' which is declared here on type 'DetailedHTMLProps<LiHTMLAttributes<HTMLLIElement>, HTMLLIElement>'}</li>
                ))}
              </ul>

</div>

Answer №1

Issue (clarified)

The problem you are facing arises from attempting to directly render the entire item object within the <li> element in React. However, React requires a valid ReactNode to be rendered, which an object is not. Therefore, we need to extract the specific property we want to display.

Resolution

To resolve this issue, we must specify which property of the item object should be displayed. For example, let's display the name property. See below for the updated code:

import React from 'react';
import { Med, medications } from './Medications';

export default function Home() {
  const filteredOralData = medications.filter((med) => med.drugClass === 'Oral');

  return (
    <div>
      <ul className="list-group">
        {filteredOralData.map((item, index) => (
          <li key={index}>{item.name}</li>
        ))}
      </ul>
    </div>
  );
}

Modifications made:

  1. Added import React from 'react'; statement to bring in the React library.
  2. Inserted key={index} into each <li> element to assign a unique identifier to every item in the list (as required by React for efficient rendering).
  3. Changed {item} to {item.name} to ensure only the drug name is displayed within the <li> element.

Answer №2

This solution actually worked!

<ul className="list-group">
  {filteredOralData.map((item) => (
    <li key={item.name}>
      {/* Display desired information here */}
      Name: {item.name} | Dosage: {item.dosage} | Drug Class: {item.drugClass}
    </li>
  ))}
</ul>

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 TypeScript error code TS2339 is indicating that the 'modal' property is not recognized on the type 'JQuery'

I'm currently utilizing Typescript with AngularJS and have encountered an issue with modals when using the typed definition of jQuery library. The specific error message I am receiving is: 'error TS2339: Property 'modal' does not exist ...

Tips on aligning a v-btn alongside v-expansion-panels on the same row

Struggling with aligning my layout. Trying to get a single set of v-expansion-panels and a v-btn in the same row, both visually centered within a card. I managed to almost achieve it in this codepen: https://codepen.io/anzuj/pen/PoPPbdw with the following ...

Using percentages to position Div elements

Currently, I am working on an HTML page that requires a div element spanning the full width of the page. My goal is to arrange other divs within this full-width div using percentages rather than pixels. The class associated with this div is .question. Thi ...

What are the steps to hosting a Laravel and Inertiajs (React) application on cPanel?

After developing a Laravel app using Inertia.js, the next step is to deploy it on a hosting platform. I initially tried deploying with Siteground but encountered an issue as they do not support NPM! Currently, I am attempting to deploy using cPanel. Here ...

JavaScript/CSS memory matching game

Just starting out in the world of programming and attempting to create a memory game. I've designed 5 unique flags using CSS that I want to use in my game, but I'm feeling a bit stuck with where to go next. I understand that I need some function ...

Leveraging custom properties in HTML elements with JavaScript

I am in the process of creating a straightforward battleships game that utilizes a 10x10 table as the playing grid. My goal is to make it easy to adjust the boat length and number of boats, which is why I'm attempting to store data within the HTML obj ...

Tips for setting React state using variables as keys or values

Although I managed to achieve the desired result, I'm still puzzled as to why my more straightforward approaches didn't work. Can someone help me understand what's going on here? Basically, I needed to set nested state at different levels u ...

What is the process for launching a TypeScript VS Code extension from a locally cloned Git repository?

Recently, I made a helpful change by modifying the JavaScript of a VSCode extension that was installed in .vscode/extensions. Following this, I decided to fork and clone the git repo with the intention of creating a pull request. To my surprise, I discove ...

Tips for positioning a chat box at the bottom of a v-card's visible area

My goal is to create a chat app using Vuejs 3 and Vuetify 3, but I'm encountering an issue aligning the chatbox with the v-card component. Instead of being positioned at the bottom of the v-card, the chatbox (green) appears at the bottom of the page. ...

The NextJS application briefly displays a restricted route component

I need to ensure that all routes containing 'dashboard' in the URL are protected globally. Currently, when I enter '/dashboard', the components display for about a second before redirecting to /login Is there a way to redirect users to ...

Choose the dropdown value that corresponds to the name of the subcollection from which to retrieve data

functions: const [damta, setDamta] = useState([]); const [drpcrs, setDrpcr] =useState("") console.log(drpcrs) const crsval = (value) =>{ if(drpcrs == value.fYCS){ return FYCS }else if (drpcrs == value.sYCS){ return SYC ...

Tips for incorporating the ternary operator in JSX of a React component while utilizing TypeScript?

I am looking to implement a conditional rendering logic in React and TypeScript, where I need to return null if a specific condition is met, otherwise render a component using a ternary operator. Here is the code snippet I currently have: {condition1 && ...

The external typing file encounters an issue when trying to locate the relative path to its own index.d.ts file

While working on my project and using react-color as a dependency, I encountered an issue with the tsc import failing. The error message displayed: node_modules/@types/react-color/lib/components/sketch/Sketch.d.ts(2,41): error TS2307: Cannot find module & ...

Encountering an error in Angular 8 with the plugin: Unhandled ReferenceError for SystemJS

I recently followed a tutorial on integrating plugins into my Angular application at this link. I'm trying to create a component in my Angular app that can execute and display an external component. However, I encountered the following error: Uncaugh ...

Utilizing fab-icons with CDN in Next.js version 13.4

Currently, I am working with the latest version of Next.js (13.4) and I would like to incorporate a single Icon into my project using Font Awesome CDN to avoid increasing the overall app size. However, when I include the following code snippet in my layou ...

Pentagon Silhouette as Header Background

I am looking to add a unique pentagon shape to my page header background without editing the HTML. I am using SASS for styling purposes. Is there a way to achieve a design similar to this wireframe image of a pentagon with the middle point at the bottom, ...

Protractor typescript guide: Clicking an element with _ngcontent and a span containing buttontext

I'm struggling with creating a protractor TypeScript code to click a button with _ngcontent and span buttontext. Does anyone have any ideas on how to achieve this? The code snippet on the site is: <span _ngcontent-c6 class="braeting net-subheadi ...

What is the best way to transition this endpoint from JavaScript to TypeScript?

I'm in the process of building a chat application with the t3 stack. I've successfully created a socket endpoint using JavaScript, but now I'm facing some challenges as I try to convert it to TypeScript. import { Server } from "Socket.I ...

Is it possible to determine the search query if the search term appears within the website URL?

I'm trying to figure out which action url and name term to use when the search term is located in the middle of the URL. For instance, the HTML code below enables me to type text and upon pressing enter or the button, it redirects me to the website w ...

I'd like to know what sets next/router apart from next/navigation

Within Next.js, I've noticed that both next/router and next/navigation offer a useRouter() hook, each returning distinct objects. What is the reasoning behind having the same hook available in two separate routing packages within Next.js? ...