I am using typescript along with react in my project and I have created a simple component where I would like to map through a list and create react elements:
const FlightSchedule: React.FC<{ flightRoute: List<Entity<FlightLeg>> }> = ({flightRoute}) => flightRoute.map(route =>
<DescriptionList key={route.get('flightId')}>
<TermDescriptionGroup description={route.get('flightId')}/>
<TermDescriptionGroup description={route.get('flightDate')} topMargin/>
</DescriptionList>)
But, I get a following typescript error:
Type 'List<Element>' is missing the following properties from type 'ReactElement<any, any>': type, props, key
Why do I get this error, what am I doing wrong here?
CodePudding user response:
Unfortunately because the signature of a React.FC is that it returns a single ReactElement, your (elegant) map over the incoming list won't work - you're effectively returning a list of ReactElements.
You'll need to wrap the whole thing, as here in a Fragment, and then do the mapping inside that:
const FlightSchedule: React.FC<{ flightRoute: List<Entity<FlightLeg>> }> = ({ flightRoute }) => (
<>
{flightRoute.map((route) => (
<DescriptionList key={route.get('flightId')}>
<TermDescriptionGroup description={route.get('flightId')} />
<TermDescriptionGroup description={route.get('flightDate')} topMargin />
</DescriptionList>
))}
</>
)
