Quantcast
Channel: Active questions tagged react-native+typescript - Stack Overflow
Viewing all articles
Browse latest Browse all 6287

Render Content Dynamically from an array map function in React Native functional component and useState

$
0
0

I have a functional component to render a simple form with some input elements.

I want to be able to dynamically add input elements when the user click a button.Im using useState hook and created a onChange arrow func as follows:

  const [players, setPlayers] = useState<PlayerModel[]>([    { id: 0, firstName: "", lastName: "" },  ]);  const handleOnAddPlayerPress = () => {    let newPlayers = players;    newPlayers.push({ id: newPlayers[newPlayers.length - 1].id + 1, firstName: "", lastName: "" });    setPlayers(newPlayers);  } 

I'm rendering the players using array map function as follows:

{players.map((player, index) => {      return <Input key={index} label={`Player #${player.id}`} />;    })}

Im calling the onChange function when the user clicks the button as follows:

<Button  onPress={handleOnAddPlayerPress}  type="clear"  icon={<Icon      raised={true}      name="user-plus"      underlayColor="black"      type="font-awesome"      reverse    />  }></Button>

all together:

import React, { useState } from "react";import { ScrollView } from 'react-native';import { Overlay, Input, Button, Icon } from "react-native-elements";import { PlayerModel } from "../../models/PlayerModel";export namespace AddNewTournamentForm {  export interface Props {    isVisible: boolean;    onBackdropPress: () => void;  }}export const AddNewTournamentForm = (  props: AddNewTournamentForm.Props): JSX.Element => {  const [players, setPlayers] = useState<PlayerModel[]>([    { id: 0, firstName: "", lastName: "" },  ]);  const handleOnAddPlayerPress = () => {    let newPlayers = players;    newPlayers.push({ id: newPlayers[newPlayers.length - 1].id + 1, firstName: "", lastName: "" });    setPlayers(newPlayers);  }   return (<Overlay {...props} fullScreen><ScrollView>        ...        {players.map((player, index) => {          return <Input key={index} label={`Player #${player.id}`} />;        })}<Button          onPress={handleOnAddPlayerPress}          type="clear"          icon={<Icon              raised={true}              name="user-plus"              underlayColor="black"              type="font-awesome"              reverse            />          }></Button>        ...</ScrollView></Overlay>  );};

However the layout doesn't seem to be re-rendering itself when a change occur.Another strange thing is that when I go out of this overlay and go back, only then I see the updated amount of input elements according to the num of players (which is strange because if I go out and in to the Overlay the state should be initiated).

Any suggestion? :)


Viewing all articles
Browse latest Browse all 6287

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>