skip to Main Content

I have an interface Med that has a few properties such as the drugClass, dosage, and name. I then create an array using the interface and declared a bunch of drugs. How would I filter it by drugClass and then display it to the 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>

2

Answers


  1. Chosen as BEST ANSWER

    This worked!

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


  2. Problem (explained)

    The error you’re encountering is because you are trying to render the entire item object directly within the <li> element, and React expects a valid ReactNode which an object is not, so we must extract it from the object.

    Solution

    To do this, we need to specify which property of the item you want to display. For example, you can display the name property. Here’s the modified 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>
      );
    }
    

    Changes made:

    1. Added import React from ‘react’; to import the React library.
    2. Added key={index} to each <li> element to provide a unique identifier for each item in the list (React requires this for efficient rendering and will throw warnings and/or errors if not satisfied).
    3. Changed {item} to {item.name} to display the drug name within the <li> element.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search