#form submit on component

16 messages · Page 1 of 1 (latest)

acoustic cobalt
#

Hi!
How to submit data from form to object on component, but without submit button? I have page with multiple components, and each component has a form. When I click Next or Back button (buttons are not on components), object binded to form stays empty.
Tnx!

pure galeBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

ruby fractal
#

You don't have to use a onSubmit() listener on your form element

#

maybe you could set up like a keypress listener, then if key.code == 'Enter' e.g process the request

#

or could use a button with an onClick() listener

acoustic cobalt
#

I can´t use either of that, on page (not on component) there are buttons Next and Back, and Stepper control, which all can change visible component with form. Is there any listener for components in Next.JS, for example, when components hide, then submit data to object?

ruby fractal
#

Do you mean the browser next & back buttons? Wdym by not on component?

#

I think to run a function when a component demounts

#

you could do something like

useEffect(() => {
  return () => {
    //Code here for demounting
  }
},[])
acoustic cobalt
#

No, I have custom next/back buttons. Here is how it looks like: return ( <div> <div className={${index === 0 ? 'mb-10 w-full' : 'hidden'}`}>
<ComponentOne test={test1}/>
</div>

  <div className={`${index === 1 ? 'mb-10 w-full' : 'hidden'}`}>
    <ComponentTwo test={test2}/>
  </div>
  
  <button onClick={back} className='m-5'>Previous</button>
  <button onClick={next} className='m-5'>Next</button>
</div>

)`

#

and in ComponentOne and ComponentTwo i have a form with testObject binded on

#

So. the problem is when i change something on form (on ComponentOne or ComponentTwo) and click Next/Previous button, object doesn´t change on page (because there is no submit button on components)

ruby fractal
#

Because the objects you are passing to the child exist in the parent component

#

you'll also need to pass the setter function from useState() down into the props

#

And then you could do something like

export default function ComponentOne({ test1, setTest1 }) {
    return (
        <div>
            <p>{test1}</p>
            <input onChange={ (e) => { setTest1(e.target.value)}}>Change value here</input>
        </div >
  )

}

By doing this, you're using the set function from the parent state to that testObject to actually make changes to react state

acoustic cobalt
#

Great! Thanks a lot, this works!