0

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>

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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> 
            })}
        </>

    )
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.