Home > Blockchain >  TypeScript React - iterate over props object
TypeScript React - iterate over props object

Time:07-04

When using TypeScript how do you loop through an object within a React (or SolidJS) components HTML? is there a correct syntax or does it require a work around?

export default function MyComponent(props: any) {
       
    return (
        <>
            {Object.values(props.someObject).map(value => {
                <div>{value.name}</div>       {/* Error: Object is of type 'unknown'. */}
            })}
        </>

    )
}

I'm following this SolidJS tutorial for context: https://youtu.be/WSvmEG7HPyE Specifically id like to use the <For> loop component built into SolidJS which I believe is just a shorthand syntax of map.

<For each={props.someObject}>
{value =>
    <div>{value.name}</div>       {/* Error: Object is of type 'unknown'. */}
}
</For>

CodePudding user response:

A simple function like this would be useful for getting the props entries with correct types:

const propsEntries = <T extends Record<string, unknown>>(props: T) =>
  Object.entries(props) as [keyof T, T[keyof T]][];

Then it could be used to map over props using the <For> component:

<For each={propsEntries(props)}>
   {([name, value]) => <li>{name}: {value}</li>}
</For>

demo in playground

CodePudding user response:

In React typescript you would need to do it in the following way.

type MyComponentProps = {
 someObject: object
}

export default function MyComponent(props: MyComponentProps) {
       
    return (
        <>
            {Object.values(props.someObject).map(value => {
                <div>{value}</div> 
            })}
        </>

    )
}
  • Related