0

I'm allowing the user to select a number from picker it can by any no like 1,4,6 random. When he selects a number like 3 then 3 TextInputs will be shown and he will enter something in 3 input fields and I want to save these values into an array. How can do this in react native I think I'm using a bad approach and I want someone expert who can make my code efficient and tell me how can I store values into an array.Regards

{this.state.noOfStores === 1 && (
              <TextInput
                style={[
                  styles.input,
                  {
                    backgroundColor: theme.colors.lightGray,
                  },
                ]}
                placeholder=" Name "
                keyboardType={'default'}
                placeholderTextColor="gray"
              />
            )}

            {this.state.noOfStores === 2 && (
              <View>
                <TextInput
                  style={[
                    styles.input,
                    {
                      backgroundColor: theme.colors.lightGray,
                    },
                  ]}
                  placeholder=" Name "
                  keyboardType={'default'}
                  placeholderTextColor="gray"
                />
                <TextInput
                  style={[
                    styles.input,
                    {
                      backgroundColor: theme.colors.lightGray,
                    },
                  ]}
                  placeholder=" Name "
                  keyboardType={'default'}
                  placeholderTextColor="gray"
                />
              </View>
            )}
            {this.state.noOfStores === 3 && (
              <View>
                <TextInput
                  style={[
                    styles.input,
                    {
                      backgroundColor: theme.colors.lightGray,
                    },
                  ]}
                  placeholder=" Name "
                  keyboardType={'default'}
                  placeholderTextColor="gray"
                />
                <TextInput
                  style={[
                    styles.input,
                    {
                      backgroundColor: theme.colors.lightGray,
                    },
                  ]}
                  placeholder=" Name "
                  keyboardType={'default'}
                  placeholderTextColor="gray"
                />
                <TextInput
                  style={[
                    styles.input,
                    {
                      backgroundColor: theme.colors.lightGray,
                    },
                  ]}
                  placeholder=" Name "
                  keyboardType={'default'}
                  placeholderTextColor="gray"
                />
              </View>
            )}
            {this.state.noOfStores === 4 && (
              <View>
                <TextInput
                  style={[
                    styles.input,
                    {
                      backgroundColor: theme.colors.lightGray,
                    },
                  ]}
                  placeholder=" Name "
                  keyboardType={'default'}
                  placeholderTextColor="gray"
                />
                <TextInput
                  style={[
                    styles.input,
                    {
                      backgroundColor: theme.colors.lightGray,
                    },
                  ]}
                  placeholder=" Name "
                  keyboardType={'default'}
                  placeholderTextColor="gray"
                />
                <TextInput
                  style={[
                    styles.input,
                    {
                      backgroundColor: theme.colors.lightGray,
                    },
                  ]}
                  placeholder=" Name "
                  keyboardType={'default'}
                  placeholderTextColor="gray"
                />
                <TextInput
                  style={[
                    styles.input,
                    {
                      backgroundColor: theme.colors.lightGray,
                    },
                  ]}
                  placeholder=" Name "
                  keyboardType={'default'}
                  placeholderTextColor="gray"
                />
              </View>
            )}
Zaid Qureshi
  • 155
  • 3
  • 12

3 Answers3

1

Use this I hope it'll solve your problem. If you need any assist in following code let me know.

import React, {Component} from 'react';
import {View, TouchableOpacity, Text, TextInput} from 'react-native';
export class AddInputs extends Component {
  state = {
    textInput: [],
    inputData: [],
  };

  //function to add TextInput dynamically
  addTextInput = index => {
    let textInput = this.state.textInput;
    textInput.push(
      <TextInput
        style={{
          height: 40,
          width: '100%',
          borderColor: '#2B90D8',
          borderBottomWidth: 3,
        }}
        placeholder={'Add Text'}
        onChangeText={text => this.addValues(text, index)}
      />,
    );
    this.setState({textInput});
  };

  //function to add text from TextInputs into single array
  addValues = (text, index) => {
    let dataArray = this.state.inputData;
    let checkBool = false;
    if (dataArray.length !== 0) {
      dataArray.forEach(value => {
        if (value.index === index) {
          value.text = text;
          checkBool = true;
        }
      });
    }
    if (checkBool) {
      this.setState({
        inputData: dataArray,
      });
    } else {
      dataArray.push({text: text, index: index});
      this.setState({
        inputData: dataArray,
      });
    }
  };

  render() {
    return (
      <View
        style={{
          flex: 1,
        }}>
        <View
          style={{
            width: '100%',
            alignItems: 'center',
          }}>
          {this.state.textInput.map(value => {
            return value;
          })}
        </View>

        <TouchableOpacity
          onPress={() => {
            this.addTextInput(
              'your desired number of inputs here like 5, 20 etc',
            );
          }}>
          <Text>Add Inputs</Text>
        </TouchableOpacity>
      </View>
    );
  }
}
Asmat ullah
  • 681
  • 8
  • 23
0

You can do something like that:

    this.state = { values: [] };
    const textInputs = [];
    for(let i=0; i< this.state.noOfStores; i++) {
          textInputs.push(
                <TextInput
                      style ={[styles.input,{ backgroundColor: theme.colors.lightGray }]}
                      placeholder=" Name "
                      keyboardType={'default'}
                      placeholderTextColor="gray"
                      onChangeText={text => this.onChangeText(text,i)}
                 />
           )
           this.setState({ values: [...this.state.values, ''] });
    }
    onChangeText = (text,index) => {
           const values = [...this.state.values];
           values[index] = text;
           this.setState({ values });
    }

Then in render method:

<View>
     {textInputs}
</View>
D10S
  • 1,468
  • 2
  • 7
  • 13
0

You can something like below, setting an array with a given length based on your picker and showing the UI based on that.

The setRows sets the number of rows and you can update the array easily.

Call the setRows from your picker.

export default function App() {
  const [textArr, setTextArr] = useState([]);
  
  const onChangeText = (text, index) => {
    const arr = [...textArr];
    arr[index] = text;
    setTextArr(arr);
  };

  const  setRows=(rowCount)=>{
   setTextArr(Array(rowCount).fill('Default text'))
  };

  return (
    <View style={{ paddingTop: 100 }}>
      <Button
        title="set"
        onPress={()=>setRows(6)}
      />
      {textArr.map((item, index) => (
        <TextInput
          style={[styles.input, { backgroundColor: 'grey' }]}
          placeholder=" Name "
          keyboardType={'default'}
          placeholderTextColor="gray"
          value={item}
          onChangeText={(text)=>onChangeText(text,index)}
        />
      ))}
    </View>
  );
}
Guruparan Giritharan
  • 15,660
  • 4
  • 27
  • 50