Search code examples
javascriptreactjsarraysreact-bootstrapinput-field

How do I display any number of input text field on a modal depending on number of element in an array


Hello i'm new to ReactJS and Javascript. How do I display any number of textbox (input field, text input) on a modal, depending on the number of words that are in a sentence?

For example because there a 5 words in "Hope you are doing great", the number of input textfields in the modal should be 5.

I'm currently doing this:

  const [inputFields, setInputField] = useState([
    {word: ''},{word: ''},{word: ''},{word: ''},{word: ''}
])

and

<InputGroup className="mb-3">
            {inputFields.map((inputField, index) => (
              
                <Form key={index}>
                    <Form.Control label="word" name="word" value={inputField.word} />
  
                </Form>

            ))} 
           
        </InputGroup>

but its manual and i'd love to make it work dynamically on it's own.

I count the number of words as per usual:

 const handleShow = (poem) => {
  var lyric = poem.lyrics;
  var words_array = lyric.split(' ')
  var words_num = words_array.length
  console.log(words_num)
  setShow(true)
};

Thanks.


Solution

  • 
    export default function DynamicInputs({poem}){
       const [inputFields, setInputField] = useState([])
    
    
       useEffect(() => {
         setInputField(poem.lyrics.split(' ').map(word => ({word})))     
       }, [poem])
    
       return (
         <>
           {
            inputFields.map((field, index) => (
              <input type="text" key={index}/>
            )) 
           }
         </>
       )
    
    }