Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

162
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda