Home > Back-end >  React form input values in JS
React form input values in JS

Time:02-24

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.

CodePudding user response:

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' 
    }
   **/
}

CodePudding user response:

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)
   }
}
  • Related