I want to make multiple copies of Form2 React Component with click event, but the code not working as I want, I am new in react so can anybody help me.
const Comform = () => {
const Form2 = () => {
return(
<div className="card" id='form-card2'>
<input className="form-check-input" type="checkbox" value="" id="options-check" onClick={Optionscheck} />
</div>
);
}
const Replica = () {
<Form2/>
}
return(
<button type="button" className="btn btn-success" onClick={Replica}>Add</button>
);
}
Keep a state as the replica counter and render the number of items you want using Array.from and Array.prototype.map.
Try like this:
const Form2 = () => {
return (
<div className="card" id="form-card2">
<input
className="form-check-input"
type="checkbox"
value=""
id="options-check"
// onClick={Optionscheck}
/>
abcd
</div>
);
};
const Replica = () => {
const [replicaCount, setReplicaCount] = React.useState(0);
return (
<div>
<button
type="button"
className="btn btn-success"
onClick={() => setReplicaCount((prev) => prev + 1)}
>
Add
</button>
{Array.from({ length: replicaCount }).map((_, index) => (
<Form2 key={index}/>
))}
</div>
);
};
ReactDOM.render(<Replica />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>
Summary
You would have to create a handler for the replica button and a state that tracks how often the button was clicked, so that you are able to render as much form items as the button was clicked.
Example
import { useState } from "react";
import "./styles.css";
const FormItem = () => (
<div className="formItem">
<label>Check me</label>
<input type="checkbox" />
</div>
);
const ReplicaButton = ({ addFormItem }) => (
<button onClick={addFormItem}>Add more</button>
);
export default function Form() {
const [formCount, setFormCount] = useState(1);
const addFormItem = () => setFormCount(formCount + 1);
return (
<div>
<form className="formius">
{Array(formCount)
.fill(null)
.map(() => (
<FormItem />
))}
</form>
<ReplicaButton addFormItem={addFormItem} />
</div>
);
}