0

I am quite new to ReactJS and still playing with the basic concepts, so the answer to my question might look obvious for pros ;)

I have a component as below:

import React from "react";

function NameList(props) {
  const names = ["Bruce", "Clark", "Diana"];
  return (
    <div>
      {names.map((x) => {
        <h1>{x}</h1>;
        console.log({ x });
      })}
    </div>
  );
}

export default NameList;

Can someone tell me why the h1 tags are not rendered while the values are written in the console?

2 Answers 2

2

You will need to return something from a map() function:

import React from "react";

function NameList(props) {
  const names = ["Bruce", "Clark", "Diana"];
  return (
    <div>
      {names.map((x) => {
        console.log(x);
        return <h1>{x}</h1>;
      })}
    </div>
  );
}

export default NameList;

Or direct return like this:

import React from "react";

function NameList(props) {
  const names = ["Bruce", "Clark", "Diana"];
  return (
    <div>
      {names.map((x) => (
        <h1>{x}</h1>
      ))}
    </div>
  );
}

export default NameList;
Sign up to request clarification or add additional context in comments.

Comments

1

Just add return before the <h1> tag based on the syntax which have been used:

function NameList(props) {
  const names = ["Bruce", "Clark", "Diana"];
  return (
    <div>
      {names.map((x) => {
        console.log({ x });
        return <h1>{x}</h1>;
      })}
    </div>
  );
}

Edit relaxed-feather-frdd9

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.