preventDefault() does not work

Asked

Viewed 186 times

0

Good evening, I’ve searched all the forum on the internet and I haven’t found anything to solve my problem. I’m studying React, and I’m trying to submit a form, but I don’t want the page to Reload when I submit the form, so I’ll use preventDefault(). But for some reason the function is not working, when I click the form button is sent normally. Follow the code:

function prevent(e) {
    e.preventDefault();
    }

return(
    <>
    <Template>
        <Container>
            <form onSubmit={(e) => prevent(e)}>
                <FormField
                label='Titulo:'
                type='text'
                placeholder='Titulo para a noticia'
                value={values.title}
                name='title'
                onChange={handlerValue}
                />
                <FormField
                label='Link:'
                type='text'
                placeholder='Link para a noticia'
                value={values.link}
                name='link'
                onChange={handlerValue}
                />
                <button className='my-2'>Adicionar</button>
            </form>
            <ul>
                {aux.map((item, indice) => {
                    return(
                        <li key={aux + indice}>
                            {aux}
                        </li>
                    )
                })}
            </ul>
        </Container>
    </Template>
    </>
)

2 answers

0

Let’s go to a code I made:

<div id="root"></div>
const App = () => {
  function stopForm (event) {
    console.log('Chamou o stopForm');
    event.preventDefault();
    console.log('Acabou o stopForm');
  }
  
  return (
    <form onSubmit={stopForm}>
      <input
        type="submit"
        value="Enviar valores"
      />
      <button>
        Enviar valores 2
      </button>
      <button type="button">
        Enviar valores 3
      </button>
    </form>
  )
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

I created 3 elements that are buttons, but only 2 have the same behavior:

  • <input type="submit" />: This guy’s gonna shoot the form Ubmit;
  • <button>: This guy’s gonna shoot the form Ubmit;
  • <button type="button">: The default button type is submit. So that this does not occur, and you wish to map a onClick just put the type="button".

0


Try to change your call from onSubmit for:

<form onSubmit={prevent}>
  • And why would that make a difference?

  • What I understand is that by default the created function already receives the Event from where it is being called.

  • In fact, it should perform in exactly the same way. This change only prevents the creation of an unnecessary anonymous function, but in no way changes the behavior of the component. https://codesandbox.io/s/bold-glitter-8lxbp?file=/src/App.js

Browser other questions tagged

You are not signed in. Login or sign up in order to post.