birdevrae
birdevrae

Reputation: 3

Nothing rendering in map loop, even though data is there

I have a React component that makes a call to a PHP endpoint that returns an array of folders in a directory (Intended to be a file browser for internal forms). The API call works, and I verify that the response is coming through as it should. However when I map over the array, nothing is rendered at all.

I've even ran chrome debugger with breakpoints, and the map statement is looped through.

const FileBrowser = () => {
  const [folders, setFolders] = useState([]);
  
  useEffect(() => {
    const fetchFolders = async () => {
      const { data } = await getFormFolders(); //API call that uses Axios.
      setFolders(data);
    }
    fetchFolders();
  }, [])
  
  return(
    <div>
      {folders.length > 0 && folders.map((folder) => {
        <div key={folder}>{folder}</div>
      })}
    </div>
  )
}

What is going on here? I am expecting a list of folder names to appear, but there is nothing at all. I even set font size to something ridiculous in case it was hiding behind nav elements, but didn't change anything. I also embedded a {console.log(folder)} within the return statement, and I can indeed see the expected names in the console.

Upvotes: 0

Views: 48

Answers (2)

Tolumide
Tolumide

Reputation: 984

Change

<div>
  {folders.length > 0 && folders.map((folder) => {
    <div key={folder}>{folder}</div>
  })}
</div>

to:

<div>
  {folders.length > 0 && folders.map((folder) => 
    <div key={folder}>{folder}</div>
  )}
</div>

You need to return whatever you're mapping through and an arrow function this way implicitly means return

Upvotes: 1

Shubham Khatri
Shubham Khatri

Reputation: 281636

You need to return JSX from within your map function. You a missing a return statement.

return(
    <div>
      {folders.length > 0 && folders.map((folder) => {
        return <div key={folder}>{folder}</div>
      })}
    </div>
  )

Upvotes: 4

Related Questions