Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

187
Visualizações
How to add a new textfield on button click and add integer value of that input field to an array in react

I want to add a new input field on button click and add the integer value of that input field to an array in react

const [price, setPrice] = useState([])
const [count, setCount] = useState([1])

const addNewTextField = () => setCount(prev => [...prev,1])

const addInputValue= () => {
   setPrice()
   console.log(price)
}

<Button onClick={addNewTextField}>Add TextField</Button >
{
   count.map((item, i) => {
   return (
    <TextField   key={i} value={item.value} id={i}  type='text' />
      )
    })
 } 

<Button onClick={addInputValue}>submit</Button >

first input value is 100, second input value is 200, result should be like this when I add new input field: [100,200]

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Try like below. You can keep only price state.

import { useState } from "react";

const App = () => {
  const [price, setPrice] = useState([""]);

  const addNewTextField = () => setPrice((prev) => [...prev, ""]);

  const addInputValue = (i, newValue) => {
    console.log(i, newValue);
    setPrice((prevState) =>
      prevState.map((value, valueIndex) =>
        valueIndex === i ? newValue : value
      )
    );
  };

  console.log(price);

  return (
    <>
      <button onClick={addNewTextField}>Add TextField</button>;
      {price.map((item, i) => {
        return (
          <input
            key={i}
            placeholder={`input ${i}`}
            // value={item}
            id={i}
            type="text"
            onChange={(e) => addInputValue(i, e.target.value)}
          />
        );
      })}
      <button onClick={addInputValue}>submit</button>
    </>
  );
};

export default App;

Code sandbox

about 4 years ago · Juan Pablo Isaza Relatório

0

   const [price, setPrice] = useState([]);
   const [count, setCount] = useState([1]);
   const [value, setValue] = useState("");
            
   const addNewTextField = () => setCount(prev => [...prev,prev + 1]);
            
   const addInputValue= () => {
         setPrice(price.concat(value));
         console.log(price)
   }
        
   return(   
    <div>
       <Button onClick={addNewTextField}>Add TextField</Button >
       {
         count.map((item, i) => {
         return (
             <TextField   key={i} value={value} id={i}  type='text' 
             onChange={e => setValue(e.target.value)} />
         );
       })
     } 
            
      <Button onClick={addInputValue}>submit</Button >
    </div>
  );

    

Button and TextField components:

function Button(props){
   return(
   <button onClick={props.onClick}>{props.children}</button>
);
}

function TextField(props){
   return(
     <input type="text" id={props.id} value={props.value}
     onChange={e=>props.onChange(e)}>
);
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda