I have created a component to dynamically create a textbox based on button click
import React, { useState } from "react";
import ReactDOM from "react-dom";
const Input = () => {
return <input placeholder="Your input here" />;
};
const Form = () => {
const [inputList, setInputList] = useState([]);
const onAddBtnClick = (event) => {
setInputList(inputList.concat(<Input key={inputList.length} />));
};
return (
<div>
{inputList}
<button onClick={onAddBtnClick}>Add input</button>
</div>
);
};
ReactDOM.render(<Form />, document.getElementById("form"));
So basically this loads a button on page load and create new textboxes everytime the "Add Input" button is clicked.
So sometimes, there can be scenarios like some values for textboxes are already available on pageload. In those cases, for example, if I have three values for TextBox available as a list ["Apple", "Mango", "Carrot"], then my page should have three TextBoxes created each with one of the values from the above list followed by the "Add Input" button
And If new textboxes are created, how to get the values of all the TextBox on button click.
Will this be possible to do in react.
Kindly guide me on how to approach this problem.
Any help is much appreciated.
Thanks,
3
Answers
I think it is, you just need to modify your
useState
to initialize the state with these values. And then, capture the values of all the text boxes when a button is clicked, so you can maintain a reference to each input element and update the state accordingly.This is another way to solve this.