1

I'm using nextjs/reactjs to create this. I'm following a youtube video tutorial, in tutorial he does the same thing and it works for him but for me it doesn't work.

Any idea?

const Index = (props) => {

  const {posts} = props;
  return(
    <div>
        {posts.map( post => (
          <h1>{post.title}</h1>
          <p>{post.body}</p>
        ))
        }
    </div>
  )
}
Index.getInitialProps = async () => {
  const data = await fetch('https://jsonplaceholder.typicode.com/posts');
  const result = await data.json();

  return {
    posts: result
  }
}

export default Index;

1 Answer 1

1

React doesn't support returning multiple components so you need to wrap them inside a parent component. For this very purpose React provides Fragment or <> </> for shorthand syntax. Change your return statement to this and it'll work:

return(
    <div>
        {posts.map( post => (
          <>
            <h1>{post.title}</h1>
            <p>{post.body}</p>
          </>
        ))
        }
    </div>
  )
Sign up to request clarification or add additional context in comments.

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.