Reputation:
I want to add new input tags to my web page when I click on Add input button.
Attempt:
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [addInput, setAddInput] = useState(false);
const handleClick = () => setAddInput(true);
return (
<div className="App">
<button onClick={handleClick}>Add Input</button>
{addInput ? <input type="text" /> : ""}
</div>
);
}
How can I make the above code work to dynamically add new inputs?
Upvotes: 1
Views: 73
Reputation: 11601
One way to do want you want.
const [state, setState] = useState([]);
const handleClick = () => {
let inputs = Object.assign([], state);
inputs.push(<input type='text' key={inputs.length} />);
setState(inputs);
}
return (
<div className="App">
<button onClick={handleClick}>Add Input</button>
{state}
</div>
);
You should know, added input
s are Uncontrolled Components.
In order to help you to learn more about the possible solutions, here is another approach:
const [state, setState] = useState(0);
const handleClick = () => setState(state + 1);
const generateInputs = () => {
const inputs = [];
for (let i = 0; i < state; i++) inputs.push(<input key={i} type='text' />);
return inputs;
}
return (
<div className="App">
<button onClick={handleClick}>Add Input</button>
{generateInputs()}
</div>
);
Upvotes: 1