skip to Main Content

I have an array of names to which I add elements like this within a function:

const [names, setNames]  =useState([])
for (const file of allFiles){
    setNames([...names, String(file)])
}

return (
    {names && names.map((name) => (
        <p>{name}</p>
))}
)

What puzzles me is that what gets printed to the website is every file name, one after the other on the same line. So every new name replaces the last until we reach the last name, and the only name that appears is the last name. However, I’d like to display every name on a new line. How can I achieve this?

2

Answers


  1. I’m not sure how you’re structuring your code, but you need to set the state names only once at the end after your loop / your logic with files using the allFiles array.

    It’s as simple as doing setNames(allFiles) for the state to represent all the files in an array.

    Also if you need to execute some code whenever the state that represents the files changes, or whenever the page is initially loaded, I suggest you look into the useEffect hook.

    Login or Signup to reply.
  2. as mentioned in other answers you might want to look at something like this:

    import React from 'react';
    import { useState, useEffect } from 'react';
    
    export function App(props) {
      const allFiles = ['fileone.jpg','filetwo.jpg','filethree.jpg']
      const [names, setNames] = useState([]);
    
      useEffect(() => {
        setNames(allFiles.map((file) => String(file)))
      }, []);
    
      return (
        names.map((name) => (<p key={name}>{name}</p>))
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search