Sadequs Haque
Sadequs Haque

Reputation: 159

What is the best way to add additional input field on a button click?

I am wondering what is the standard way to add additional input field from onClick() on a button. A scenario might be adding a Todo-list item field on click.

My approach was having a state array that stores the actual component and concat the array.

const[ComponentList, setComponentList] = useState([<Component id={1}/>]);

And then...

function addAnotherQuestion() {
    setComponentList(ComponentList.concat(generateComponent(currentID)));
 }

I was told this is a very bad idea and I would end up with messed up inputs because of stale states (which I did, and then I solved by writing to Redux store directly from the child component). This is not an ideal solution, so I want to know what is the standard way to do this?

Upvotes: 1

Views: 141

Answers (2)

Achim
Achim

Reputation: 247

How about keeping an array of Id's instead of components?

const[ComponentListIds, setComponentListIds] = useState([1]);

Why do you need to generate the components? What you should probably do, is generating new Id's instead. And then render the components within the render part of you component with:

render(
...
ComponentListIds.map(id=> <Component key={id} id={id}>)
...
)

Upvotes: 0

jmk
jmk

Reputation: 1610

I would store only inputs data in array like so:

const [inputs, setInputs] = useState(["some_id_1", "some_id_2", "some_id_3"]);
function addAnotherQuestion() {
    setInputs(inputs.concat(currentID));
}

and then render them separately:

<>
 { inputs.map((id) => <Component key={id} id={id}/>) }
</>

Upvotes: 1

Related Questions