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

386
Vistas
reactJs my event.preventDefault(); doesnt work

i try to do a form on react js and i don't want to refresh the page when i submit my form.

I do a callback on my server (flask).

When i try to do :"event.preventDefault();" my call to my flask server doesn't work.

there is my code:

import { useState } from 'react';


const Form = (props) => {

  const componentDidMount = (event) => {
      event.preventDefault();

    // Simple POST request with a JSON body using fetch
    
    const requestOptions = {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: title })
    };
    
    fetch('http://localhost:5000/add', requestOptions)
    
        .then(response => response.json())
        
        .catch(error => console.log(error))
        
      
  }
  const [title, setTitle] = useState('')
  const [body, setBody] = useState('')


return (
     <div>
        <form onSubmit = {() => componentDidMount()} >

            <label htmlFor="title" className="form-label">Title</label>
                    <input 
                    type="text"
                    className="form-control" 
                    placeholder ="Enter title"
                    value={title}
                    onChange={(e)=>setTitle(e.target.value)}
                    required
                    />

                    <label htmlFor="body" className="form-label">Body</label>
                    <textarea 
                    className="form-control" 
                    placeholder ="Enter body" 
                    value={body}
                    onChange={(e)=>setBody(e.target.value)}
                    required
                    >
                    </textarea>

                    <button 
                    className="btn btn-primary mt-2"
                    >
                    Publish article</button>

                    </form>
    </div>
)}

export default Form;

I don't want to refresh the page cause one in two my callback function and i want to work on it but i can't read the error on the console.

Thanks for your help!

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

you need to pass event as well to trigger event.preventDefault() function

<form onSubmit = {(event) => componentDidMount(event)} >
about 4 years ago · Juan Pablo Isaza Denunciar

0

It is because you are calling the function componentDidMount in form tag.

You just have to pass the reference of the function in the onSubmit attribute.

<form onSubmit={componentDidMount}>
...
</form>
about 4 years ago · Juan Pablo Isaza Denunciar

0

I wouldn't recommend to use a component lifecycle method (like componentDidMount) to handle a form submission event. You could just create a specific handler:

const Form = (props) => {

    const handleSubmit = (event) => {
        event.preventDefault();
        // ...
    }
    // ...


    return (
        <div>
            <form onSubmit={handleSubmit} > 

                {/* // ... */}
            </form>
        </div>
    )
}
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