How to display arrays as Jsx elements in reactjs

280 views Asked by At

There is this users array in which the user names are stored in the photo are split from the photo array and i want to display the array results as buttons are displayed . The code snippet is below

let users: string[] = [];
const setUserNames = photo.filepath.split("_")[1];
users.push(setUserNames);
console.log(`Name ->`, users);
return (
   <IonRow>
     {users.map((users, index) => (
        <IonButton key={index}>{users}</IonButton>
      ))}
    </IonRow>
)
1

There are 1 answers

1
Vishal Sakaria On

Be careful,

users.push(setUserNames) is mutable and doesn't adhere to the way data is changed in React. You need to change user using useState and spread operators.

Moreover, I'd advise you do all your array building in the seperate function and return a user array and then set that array to some state using useState.

Then start building the UI using JSX

Something like this.

const SomeCom = (props) => {
    const [users, setUsers] = useState(buildUserArray(props.photos))
    return (
        users.map(() => {
            // Render your JSX
        })

    )
}