Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Dynamically render component for each item in array React Native

Beginner question here, not sure exactly what this would be considered, but I’m trying to make a form where a user can add and remove input rows upon pressing a button. What do I need to change to render new components or remove components when the Add or Remove buttons are pressed? Right now, the Add and Remove button change the textInput array appropriately, but components are not actually being added or removed.

Here is my current code:

FormScreen.js

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import React from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';
import { Button, Caption } from 'react-native-paper';
import InputCard from '../components/InputCard';

const FormScreen = props => {
    const textInput = [1,2,3];

    const addTextInput = () => {
        let currArr = textInput;
        let lastNum = currArr[currArr.length -1]
        let nextNum = lastNum + 1
        console.log(currArr, lastNum, nextNum);
        textInput.push(
            nextNum
        );
        
        console.log(textInput);
    };
    
    const removeTextInput = () => {
        textInput.pop();
        console.log(textInput);
    };

    return (
        <ScrollView>
            <View style={styles.col}>
                <View style={styles.row}>
                    <Caption>Favorite colors?</Caption>
                </View>
                <View style={styles.row}>
                    <View>
                    {textInput.map(key => {
                        return (
                            <InputCard key={key}/>
                        );
                    })}
                    </View>
                </View>
                <View>
                    <View style={styles.col}>
                        <Button title='Add' onPress={() => addTextInput()}>Add</Button>
                    </View>
                    <View style={styles.col}>
                        <Button title='Remove' onPress={() => removeTextInput()}>Remove</Button>
                    </View>
                </View>
            </View>
        </ScrollView>
    );
};

export default FormScreen;

InputCard.js

import React, { useState } from "react";
import { View, StyleSheet } from 'react-native';
import { Caption, Card, TextInput } from "react-native-paper";

const InputCard = (props) => {

    const [input, setInput] = useState('');
    
    return (
        <View>
            <Card>
                <Card.Content>
                    <Caption>Item {props.key}</Caption>
                    <View style={styles.row}>
                        <View style={styles.half}>
                            <TextInput
                                label="Input"
                                value={input}
                                onChangeText={input => setInput(input)}
                                mode="outlined"
                                style={styles.textfield}
                            />
                        </View>
                    </View>
                </Card.Content>
            </Card>
        </View>
    );
}

export default InputCard;

>Solution :

Instead of storing it in a array, try to do something like this, using 2 states.

const [totalTextInput, setTotalTextInput] = useState([])//initial state, set it to any data you want.
const [count, setCount] = useState(0);

const addTextInput = () => {
  
      setCount((prevState) => prevState + 1);
      setTotalTextInput((prevState) => {
        const newTextInput = Array.from(prevState);  // CREATING A NEW ARRAY OBJECT
        newTextInput.push(count);
        return newTextInput;  
      });
    };

const removeTextInput = () => {
  setTotalTextInput((prevState) => {
    const newTextInput = Array.from(prevState);  // CREATING A NEW ARRAY OBJECT
    newTextInput.pop();
    return newTextInput;  
  });
};

And in your code:

<View>
      {totalTextInput.map(key => {
           return (
                <InputCard key={key}/>
            );
       })}
</View>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading