Home > Enterprise >  Create Inputs Dynamically in react native
Create Inputs Dynamically in react native

Time:04-11

I want to create inputs dynamically in react native, for example if value is 3 , it should create three input components , if value is 2 it should have 2 inputs.

Please check my code below

 const [myloop, setMyloop] = React.useState([]);

  const renderButtons = (data) => {
    for (let i = 0; i < data; i  ) {
      myloop.push(
        <Input
          placeholder="Name"
        />
      );
    }
  };
  renderButtons(2);

In my main function i have slider , which if i set some value i need to create that number of inputs..

return (<View>

 <Slider
     minValue={1}
     maxValue={4}
     onChange={(v) => {
                renderButtons(Math.floor(v));
              }}
          
         
   </Slider>
 
{myloop}

</View>)

here the problem is its creating lots of inputs dynamically , How do i create dynamic inputs properly.

Also when i try to reset the array using setMyloop([]); i get following error

Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

CodePudding user response:

const [size, setSize] = useState(0);

return (
  <View>
    <Slider
      minValue={1}
      maxValue={4}
      onChange={(v) => setSize(v)}>
    </Slider>
   {renderButtons(size)}
  </View>
);

Then

const renderButtons = (size) => {
  <>
  {for (let i = 0; i < size; i  ) {
    <Input
      placeholder="Name"
    />
  }}
  </>
};

CodePudding user response:

One of the solution you can use is by using the map function inside your JSX:

For a Reactjs application, you can use the following code:

import { useEffect, useState } from "react";

const DEFAULT_VALUE = 0;

export default function App() {
  const [inputNumber, setInputNumber] = useState(DEFAULT_VALUE);
  const [inputArray, setInputArray] = useState(new Array(1).fill(0));

  useEffect(() => {
    setInputArray(new Array(parseInt(inputNumber)).fill(1));
  }, [inputNumber]);

  return (
    <div>
      <input
        type="range"
        min="0"
        max="100"
        value={inputNumber}
        onChange={(v) => setInputNumber(v.target.value)}
      />
      {inputArray.map((each, index) => (
        <input
          key={index}
          type="text"
          value={"INPUT NUMBER "   index}
          onChange={() => {
            console.log(index);
          }}
        />
      ))}
    </div>
  );
}

For your React Native application, replace the following components:

  • div -> View
  • input (type="range") -> Slider
  • Depending of what is returning the Slider you can replace v.target.value by v as you previously write in your code
  • The parseInt() is maybe not necessary for your Slider component
  • Related