skip to Main Content

I have initialized a state object to store the dynamically added input elements by a user via a button they click. In this input element, a user can type a number. I’m trying to get the number value and value of every element that is dynamically added but I am not sure how to exactly do that.

My code:

   const [addedExpenses, setAddedExpenses] = useState([]);

   function addExpense() {
      const userNewExpense = (
         <div class ="new-expense">
            <input id="written-expense"></input>
              <input id="money-expense" ></input>
        </div>
    )
    setAddedExpenses([...addedExpenses, userNewExpense])
 

3

Answers


  1. you can try this one.

    export default function App(){
    const [addedExpenses, setAddedExpenses] = useState([{values:''}]);/*using the state object to store the dynamically */
    const [addedExpensessingle, setAddedExpensessingle] = useState('');/*using the state to store the dynamically */
    const handleinput = (e) => {
    
    setAddedExpenses({...addedExpenses,values:e.target.value})
    setAddedExpensessingle(e.target.value)
    }
    return (
    <div className="App">
                  <input id="written-expense" onChange={handleinput}></input
    <p>{addedExpenses.values}</p>
    <p>{addedExpensessingle}</p></div>
    );
    }
    
    Login or Signup to reply.
  2. Hope this satisfies your question. React-StackBlitz . StackOverflow already has a similar question try exploring more before posting here.

    import React, { useState, useEffect } from 'react';
    import './style.css';
    export default function App() {
      const [expensesCount, setExpensesCount] = useState(1);
      const [inputVal, setInputValue] = useState([{ id: 0, val: '' }]);
      const AddNew = () => {
        setExpensesCount((pre) => pre + 1);
      };
    
      return (
        <div>
          <input type="button" value="Add New" onClick={AddNew} />
          <br />
          <div>
            {Array.from(Array(expensesCount)).map((item, i) => {
              return (
                <AddExpenses
                  i={i}
                  onInputChange={(e) => {
                    setInputValue((old) =>
                      old.map((item) => ({ id: i, val: e.target.value }))
                    );
                  }}
                />
              );
            })}
          </div>
        </div>
      );
    }
    
    function AddExpenses({ onInputChange, i }) {
      return (
        <>
          <input
            type="number"
            onChange={(e) => onInputChange(e)}
            placeholder={i + ' - Input '}
          />
          <br />
        </>
      );
    }
    Login or Signup to reply.
  3. You can do it like this :

    import "./styles.css";
    import { useState } from "react";
    
    export default function App() {
      const [count, setCount] = useState(0);
      const [values, setValues] = useState([]);
    
      const ExpenseInput = ({ id, index }) => {
        return (
          <input
            id={id}
            type="text"
            placeholder="Expense"
            style={{ margin: 8 }}
            onChange={(e) => {
              let array = values;
              array[index] = e.target.value;
              setValues(array);
            }}
          />
        );
      };
    
      //You get values of all inputs from here
      console.log("Values Expense = ", values);
    
      return (
        <div className="App">
          <input
            type="number"
            placeholder="Total elements"
            onChange={(e) => {
              const size = Number(e.target.value);
              setCount(size);
              setValues(new Array(size));
            }}
          />
    
          <div style={{ display: "flex", flexDirection: "column" }}>
            {count > 0 &&
              Array(count)
                .fill(null)
                .map((_, i) => <ExpenseInput id={"expense-" + i} index={i} />)}
          </div>
        </div>
      );
    }
    

    Or you can see the live JS :
    Live sample

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search