How do I add React component on button click?
React Hook Version
Click here for live example
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>
<button onClick={onAddBtnClick}>Add input</button>
{inputList}
</div>
);
};
ReactDOM.render(<Form />, document.getElementById("form"));
Remove {}
., it is not necessary using it in this case
{this.state.inputList.map(function(input, index) {
return input;
})}
Example
or better in this case avoid .map
and just use {this.state.inputList}
,
Example