Matt Strom
Matt Strom

Reputation: 720

Is there a better way to define the type for a list of react components?

SO Imagine you're grabbing data from an API, and building a list of Card components to display in a parent component. It might look something like this:

function App() {
    let elements = [] // what type do I put here to avoid the any type warning?
    for (let i = 0; i < someNumber; i++) {
        elements.push(<div>content goes here</div>);
    }

    render(
        <div>
            {elements}
        </div>
    );
}

Obviously putting let elements: any fixes this, but that's not very semantic/verbose in my mind. Is there a better typing system that can be used here?

Upvotes: 0

Views: 1269

Answers (3)

Rahul Sharma
Rahul Sharma

Reputation: 10071

You can create an array and fill it with some value (<div>) if you don't need it index, If you need index then use fill with map.

new Array(2).fill(<div>content goes here</div>)

OR

const someNumber = 2;
const result = new Array(2).fill(0).map((item, index) => `content ${index} goes here`)
console.log(result);

Upvotes: 0

Alex Wayne
Alex Wayne

Reputation: 187024

ReactNode from the react package is the type of rendered JSX. So to type an array of those you would use:

let elements = React.ReactNode[]

However, I really like to use a mapTimes helper function to help with things like this:

/** Returns an array of the return value of `fn` run `times` number of times. */
export function mapTimes<T>(times: number, fn: (index: number) => T): T[] {
  const arr: T[] = []

  for (let i = 0; i < times; i++) {
    arr.push(fn(i))
  }

  return arr
}

Now you can simply do:

let elements = mapTimes(someNumber, (i) => (
    <div>content #{i} goes here</div>
))

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 370729

I'd use Array.from, so you don't have to type anything manually yourself:

function App() {
    const elements = Array.from(
        { length: someNumber },
        () => <div>content goes here</div>
    );
    return (
        <div>
            {elements}
        </div>
    );
}

But you can also type the array if you wanted:

const elements: JSX.Element[] = [];

Upvotes: 1

Related Questions