Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Send array as property to component in Typescript

This should be easy, but I am struggling with type managing trying to send a list as property to a component. Specifically, I am creating the following component:

const [list, setList] = useState<Array<ToastProps>>([]);
...
<Toast toastlist={list}></Toast>

This component is set as:

export interface ToastProps {
  id: number;
  title: string;
  description: string;
  backgroundColor: string;
}

export default function Toast(props: ToastProps[]) {
  return (
    <div>
      {props.map((toast, i) => (
        <div key={i} style={{ backgroundColor: toast.backgroundColor }}>
          <button>X</button>
          <div>
            <p>{toast.title}</p>
            <p>{toast.description}</p>
          </div>
        </div>
      ))}
    </div>
  );
}

I have the following error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Type ‘{ toastlist: ToastProps[]; }’ is not assignable to type
‘IntrinsicAttributes & ToastProps[]’.

How can I fix this problem? Thanks in advance for any help you can provide.

>Solution :

the component prop should be like this.

export default function Toast({toastlist}: {toastlist:ToastProps[]}) {
 return (
    <div>
      {toastlist.map((toast, i) => (
        <div key={i} style={{ backgroundColor: toast.backgroundColor }}>
          <button>X</button>
          <div>
            <p>{toast.title}</p>
            <p>{toast.description}</p>
          </div>
        </div>
      ))}
    </div>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading