0

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>;
}
ABGR
  • 4,631
  • 4
  • 27
  • 49
Dev
  • 355
  • 1
  • 7
  • 24
  • The arrow notation written in a single like will automatically return the but inside a normal function, you have to explicitly include the `return` statement which is missing in your code. – It Assistors Jun 11 '20 at 05:59
  • https://stackoverflow.com/questions/52334319/how-is-different-from/52334964#52334964 – Bhojendra Rauniyar Jun 11 '20 at 06:00

3 Answers3

2

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)
})
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
0

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>;
Hyunwoong Kang
  • 530
  • 2
  • 9
0

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'; };
robinsax
  • 1,195
  • 5
  • 9