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

181
Visualizações
how can i add input value to state in React.js?

im trying to get input value and push it into state when the person click on submit, but i confused.

const App = () => {
    const [category,setCategory] = useState([])
    return ( 
        <div>
            <input type="text" name="" id="" />
            <button type="submit" >Add</button>
        </div>
     );
}
 
export default App;

i tried lot of ways but i coudn't find any solution.

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

0

You just need to have another state variable that stores the current input value. Like this:

const [categories, setCategories] = useState([]);
const [category, setCategory] = useState('');

const addCategory = () => {
  setCategories([...categories, category]);

  // after pushing the value, you may want to reset the input field
  setCategory('');
};

...
<input value={category} onChange={(e) => setCategory(e.target.value)} />
<button onClick={addCategory}>Add</button>

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this

const App = () => {
    const [category,setCategory] = useState([])
    const addCategory = e => {
      const newCategory = category
      newCategory.push(e.target.previousElementSibling.value)
      setCategory(newCategory)
    }
    return ( 
        <div>
            <input type="text" name="" id="" />
            <button type="submit" onClick={addCategory}>Add</button>
        </div>
     );
}
 
export default App;

If you don't want to use previousElementSibling then try useRef like this:

const App = () => {
    const catRef = useRef(null)
    const [category,setCategory] = useState([])
    const addCategory = e => {
      const newCategory = category
      newCategory.push(catRef.current.value)
      setCategory(newCategory)
    }
    return ( 
        <div>
            <input type="text" name="" ref={catRef} id="" />
            <button type="submit" onClick={addCategory}>Add</button>
        </div>
     );
}
 
export default App;

Of course you'll have to import useRef

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