Search code examples
javascriptreactjses6-map

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>;
}

Solution

  • 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)
    })