0

I am new at React and I am trying to do a very simple Todo app but I already got stuck. I initialized with create-react-app and somehow nothing is showing when I loop through the state and call a component passing data to it.

Here is the App.js:

import React, { useState } from 'react';
import Todo from './components/Todo';

function App() {
  const [title, setTitle] = useState(['test1', 'test2', 'test3'])

  return (
    <div className="App">
      {title.map(item => {
        <div>
          <Todo item={item} />
        </div>
      })}
    </div>
  );
}

export default App;

And this is the Todo.js:

import React from 'react';

const Todo = ({item}) => {
  return <div>{item}</div>
}

export default Todo;

The Todo component is called from the right folder (I checked many times), the files are saved and React is not returning any error, it just displays nothing in the DOM. If I loop through the title and display its content from the app.js it displays everything as normal. Also, a console.log from inside Todo component is not triggered meaning, somehow the component is not imported. What am I doing wrong here?

Andrea D_
  • 2,028
  • 3
  • 15
  • 38
  • 1
    You are not return anything fro your `.map` calls. You need to add `return` since you are using the block version for the arrow functions, and not the implicit return version which does not have `{}` around the body. – Gabriele Petrioli May 24 '21 at 07:20
  • yes, gosh. Such a newbie error. Thank you – Andrea D_ May 24 '21 at 07:49

2 Answers2

2

It's not displaying because you are not returning anything from map

Try something like below:-

Return from map using return keyword

      {title.map(item => {
        return (
          <div>
            <div>{item}</div>
          </div>
        )
      })}

OR implicitly return line below:-

      {title.map(item => (
        <div>
          <div>{item}</div>
        </div>
      ))}
Priyank Kachhela
  • 2,517
  • 8
  • 16
1

try something like this:

import React, { useState } from 'react';
import Todo from './components/Todo';

function App() {
  const [title, setTitle] = useState(['test1', 'test2', 'test3'])

  return (
    <div className="App">
      {title.map(item => {
       return(
        <div>
          <Todo item={item} />
        </div>
);
      })}
    </div>
  );
}

export default App;

or

 import React, { useState } from 'react';
import Todo from './components/Todo';

function App() {
  const [title, setTitle] = useState(['test1', 'test2', 'test3'])

  return (
    <div className="App">
      {title.map(item =>(
        <div>
          <Todo item={item} />
        </div>
      ))}
    </div>
  );
}

export default App;