1

I'm new to TypeScript and Next.js. I've created an index page that gets the JSON data from the mock database and after it's returned, it is supposed to dynamically create a new Block component for each object in the array using the map function.

I know that the Block component outside of the map function displays but doesn't seem to be calling the Block component while running the map function. Any ideas?

This is my index page:

import fetch from 'isomorphic-unfetch';

import {Block} from 'components/text/block';


interface Props {
  games: [{
    _id: string;
    name: string;
  }]
}

const Home: NextPage<Props> = ({games}) => {
  console.log(games);

  return (
  <div>
    {games.map((g) => {
      console.log("Inside Map " + JSON.stringify(g.name));
      <Block key={g._id} name={g.name}></Block>
    })}
    <Block key={games[0]._id} name={games[0].name}></Block>
  </div>
  )
};

Home.getInitialProps = async () => {
  const response = await fetch('http://localhost:3000/api/games')
  const games = await response.json();
  return {games};
};

export default Home;

This is my Block component:

import React from 'react';

interface Props {
  name: string;
  key: string;
}

export let Block: React.FC<Props> = ({name}) => {
  console.log("JSX Block " + name);
  return (
    <div>
      <h1>{name}</h1>
    </div>
  )
}
2

1 Answer 1

4

you are not returning anything from inside the map thus (implicit) undefined gets returned and renders nothing. you need to return your Block JSX element.

{games.map((g) => {
  console.log("Inside Map " + JSON.stringify(g.name));
  return <Block key={g._id} name={g.name}></Block>   // <----------------------
})}
Sign up to request clarification or add additional context in comments.

1 Comment

YES! This was is. Thank you

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.