Home > database >  Sending Props to functional component : TypeScript
Sending Props to functional component : TypeScript

Time:01-30

I have custom Interfaces defined like so

interface Meeting {
    Subject: string;
    Organizer: string;
    StartTime: string;
    EndTime: string;
    Participants: Participant[] | null;
}

interface Participant {
    Name: string;
    Title: string;
}

then I have a

const meetings: Meeting[] = // array of Meeting objects 

Now I try to send this like so

export const App = ():JSX.Element => {
    return <div className="app-container">
        <MainView info={meetings}/>
        <SideBar/>
    </div>

}

Error i get is for "info" , it reads

Type '{ info: Meeting[]; }' is not assignable to type 'IntrinsicAttributes & Meeting[]'.
  Property 'info' does not exist on type 'IntrinsicAttributes & Meeting[]'.ts(2322)

What is wrong here and how can I send this prop ?

Also, in receiving component there is

export const MainView = ({info}: Meeting[]):JSX.Element => {return <></>}

and error is again at 'info'

Property 'info' does not exist on type 'Meeting[]'.ts(2339)

CodePudding user response:

That is because the first argument in a JSX.Element refers to the entire prop object: so when you unpack the info key, you need to define the type as such:

export const MainView = ({ info }: { info: Meeting[] }):JSX.Element => {return <></>}

For better clarity, it makes sense to define the props for MainView separately:

interface MainViewProps {
  info: Meeting[];
}

export const MainView = ({ info }: MainViewProps):JSX.Element => {return <></>}

CodePudding user response:

Props is an object, and info is one property on that object. So you can specify the type like this:

export const MainView = ({ info }: { info: Meeting[] }): JSX.Element => 

Alternatively, there's a helper type FC for function components:

import { FC } from 'react';

export const MainView: FC<{ info: Meeting[] }> = ({ info }) => 

Note that the FC will automatically add children as a possible prop, which may not be desired.

  •  Tags:  
  • Related