Dev
Dev

Reputation: 385

map function doesn't work in React component

I'm currently learning ReactJS and I can't spot what is wrong with my code. So, I have a function and map() method inside. I have written it in 2 ways(arrow and normal) but the normal function doesn't seem work(page reloads empty but no errors or code highlights shown). Just to clarify, I don't run these functions at the same time - one is being commented out while testing another one and then I switch it. Also, the arrow function works just fine.

Could you please check my code and advice what is the problem here?

// Arrow Function which works

function App() {
const appComponent = AppData.map((data) => <Data question={data.question} answer={data.answer} />);
return <div>{appComponent}</div>;
}

// Normal Function which doesn't work

function App() {
const appComponent = AppData.map(function (data) {
    <Data question={data.question} answer={data.answer} />
});
return <div>{appComponent}</div>;
}

Upvotes: 0

Views: 521

Answers (3)

Dennis Vash
Dennis Vash

Reputation: 53874

You don't have a return statement in your #Array.map callback, currently your callback returns an array: [undefined]:

function App() {
  const appComponent = AppData.map(function (data) {
    return <Data question={data.question} answer={data.answer} />;
  });
  return <div>{appComponent}</div>;
}

See examples in #Array.map docs.

let numbers = [1, 4, 9]
let roots = numbers.map(function(num) {
    return Math.sqrt(num)
})

Upvotes: 2

robinsax
robinsax

Reputation: 1220

The trick here is that arrow functions implicitly return the value of their contained statement (unless they are wrapped with {} curly braces).

Here are the three ways to return values:

() => 'returned';
() => { return 'returned'; };
function() { return 'returned'; };

Upvotes: 0

Hyunwoong Kang
Hyunwoong Kang

Reputation: 530

You are not returning in the latter one.

function App() {
const appComponent = AppData.map(function (data) {
    return <Data question={data.question} answer={data.answer} />
});
return <div>{appComponent}</div>;

Upvotes: 0

Related Questions