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

172
Visualizações
React form input values in JS

I am using NextJS with bulma CSS to create a simple application. I have this following form:

const MyPage = () => {
const [firstName, setFirstName] = useState('')
const [secondName, setSecondName] = useState('')

const updateFirstName = event => {
    setFirstName(event.target.value)
}

const updateSecondName = event => {
    setSecondName(event.target.value)
}

const createUser = async() => {
   // Todo: perform some action with firstName and secondName
}

return (
<section className='mt-5'>
    <div className='container'>
        <div className='field'>
            <label className='label'>My Form</label>
            <div className='control'>
                <input onChange={updateFirstName} className='input' type='type' placeholder='Enter First Name'></input>
            </div>
        </div>
        <div className='field'>
            <div className='control'>
                <input onChange={updateSecondName} className='input' type='type' placeholder='Enter Second Name'></input>
            </div>
        </div>
        <button onClick={createUser} className='button is-primary'>Create</button>
    </div>
</section>
)
}
export default MyPage

I have to call updateFirstName and updateSecondName on every input change. I want to get these input field's value on createUser() function call only. Please suggest how to do it or any other better approach. I want to eliminate firstName and secondName variables, and directly access entered input in the createUser() function.

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

0

If you don't want a controlled input. You can quit managing the state and access the value old way using plain vanilla JS.

Make sure to add name attribute with all the input fields.

function createUser() {
    
   const inputs = document.querySelectorAll(".field input")
   let data = {}
   inputs.forEach(input => {
      data[input.name] = input.value
   })
   /**
    This would yield you
    {
      'firstname': 'value',
      'secondName': 'value' 
    }
   **/
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Please change your input fields as shown below:

 <input onChange={(e)=>createUser(e,'firstName')} className='input' type='type' placeholder='Enter First Name'></input>
 <input onChange={(e)=>createUser(e,'lastName')} className='input' type='type' placeholder='Enter First Name'></input>

Then in your update your createUser function as shown below:

const createUser = (event, element) => {
   if(element==='firstName') {
      setFirstName(event.target.value)
   }

   if(element==='lastName') {
      setLastName(event.target.value)
   }
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You can try alternatively with this useRef() hook,

const MyPage = () => {

const firstName = useRef();
const secondaName = useRef();

const createUser = async() => {
    
   // Todo: perform some action with firstName and secondName
   console.log(firstName.current.value, secondName.current.value)  // It will prints the value that is typed by the user in both the textfields
  
}

return (
<section className='mt-5'>
    <div className='container'>
        <div className='field'>
            <label className='label'>My Form</label>
            <div className='control'>
                <input ref={firstName} className='input' type='type' placeholder='Enter First Name'></input>
            </div>
        </div>
        <div className='field'>
            <div className='control'>
                <input ref={secondName} className='input' type='type' placeholder='Enter Second Name'></input>
            </div>
        </div>
        <button onClick={createUser} className='button is-primary'>Create</button>
    </div>
</section>
)
}
export default MyPage
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