Notification texts go here Contact Us Buy Now!

Dynamically render components in react based on conditions

const onAddBtnClick = (event) => { setInputList([...inputList,<Input key={inputList.length} />]); };
In this way you will get the previous input as well as your newly generated input element
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.
<pre>{code> import React, { useState, useRef } from "react"; import ReactDOM from "react-dom"; const Input = ({ value, onChange }) => { return <input placeholder="Your input here" value={value} onChange={onChange} />; }; const Form = () => { // Initial values for the text boxes const initialValues = ["Apple", "Mango", "Carrot"]; // State to hold the current values of the text boxes const [inputList, setInputList] = useState(initialValues.map((val, index) => ({ value: val, id: index }))); // Ref to hold references to the input elements const inputRefs = useRef([]); const onAddBtnClick = () => { // Add a new empty input field setInputList([...inputList, { value: "", id: inputList.length }]); }; const onSubmit = () => { // Get the values of all the text boxes const values = inputList.map((input, index) => inputRefs.current[index].value); console.log(values); // Log the values to see them in the console }; return ( <div> {inputList.map((input, index) => ( <Input key={input.id} value={input.value} ref={el => inputRefs.current[index] = el} onChange={e => setInputList(inputList.map((item, i) => i === index ? { ...item, value: e.target.value } : item))} /> ))} <button onClick={onAddBtnClick}>Add input</button> <button onClick={onSubmit}>Submit</button> </div> ); }; ReactDOM.render(<Form />, document.getElementById("form")); {/<code>}
This is another way to solve this.
<pre>{code> import React, { useState, useRef } from "react"; import ReactDOM from "react-dom"; const Input = (props) => { return <input {...props} placeholder="Your input here" />; }; const Form = ({ data }) => { const [inputList, setInputList] = useState([]); useEffect(() => { setInputList( data.map((item, i) => ( <Input id={`input${i}`} name={`input${i}`} key={i} defaultValue={item} /> )) ); }, [data]); const onAddBtnClick = (event) => { setInputList( inputList.concat( <Input id={`input${inputList.length}`} name={`input${inputList.length}`} key={inputList.length} /> ) ); }; const onSubmit = () => { var form = document.getElementById("form"); var formData = {}; for (var i = 0; i < form.elements.length; i++) { var element = form.elements[i]; if (element.tagName === "INPUT" && element.type !== "button") { formData[element.name] = element.value; } } console.log(formData); }; return ( <div> {inputList} <button type="button" onClick={onAddBtnClick}> Add input </button> <button type="button" onClick={onSubmit}> Submit </button> </div> ); }; ReactDOM.render(<Form data={["Apple", "Mango", "Carrot"]} />, document.getElementById("form")); {/<code>}

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.