-3

I have the following React render function:

render() {
  return (
    <h1>Post list</h1>,
    this.state.posts_data.map(p =>
      <div key={p.id}>
        {p.title} , {p.id} , {p.userId}
      </div>
    )
  );
}

Why does the h1 not appear when run the code?

Emile Bergeron
  • 14,368
  • 4
  • 66
  • 111

4 Answers4

1

You can only return 1 element, in your case you have 2 options, you can wrap all your elements in a single <div> like this:

render() {
  return (
    <div>
      <h1>Post list</h1>,
      {this.state.posts_data.map(p =>
        <div key={p.id}>
          {p.title} , {p.id} , {p.userId}
        </div>
      }
    </div>
  );
}

or you can use <React.Fragment />.

render() {
  return (
    <React.Fragment>
      <h1>Post list</h1>,
      {this.state.posts_data.map(p =>
        <div key={p.id}>
          {p.title} , {p.id} , {p.userId}
        </div>
      }
    </React.Fragment>
  );
}

Note: In React we use JSX, so if you want to use Javascript with your HTML you have to wrap it in { }, which is why I've wrapped your this.state.posts_data.map() in those brackets.

Make sure that this.state.posts_data is an Array or else this will throw an error.

Edgar Henriquez
  • 1,288
  • 1
  • 11
  • 15
1

I rewrite the code using array concept and the problem solved

 render() {
        return (
               [
                <h1>Post list</h1>,
                this.state.posts_data.map(p =>
                <div key={p.id}>
                    {p.title} , {p.id} , {p.userId}
                </div>
                )
               ]
        );

    }
-1

You have to wrap both elements in one tag. Render can only return one.

-1

I have modified your code.

render() { 
    return ( 
        [
            <h1>Post list</h1>, 
            this.state.posts_data.map(p => (
                  <div key={p.id}> 
                      {p.title} , {p.id} , {p.userId} 
                  </div>
               ) 
            )
        ]
    );
}

When you have multi element but you don't want them to wrap in a single parent node, you need to push them to array. Also you need to use curly braces around your js code within jsx.

Sameer Reza Khan
  • 423
  • 4
  • 12