prevent page refresh when submitting form in react.js-ag捕鱼王app官网

current location:home > learning > web front-end > react >

prevent page refresh when submitting form in react.js

author:jiyik last updated:2025/03/07 views:

use the method on the event object preventdefault()to prevent a page refresh when a form is submitted in react, for example event.preventdefault(). preventdefault()the method prevents the browser from issuing the default action, which in case of a form submission is to refresh the page.

import {usestate} from 'react';

const app = () => {
  const [first, setfirst] = usestate('');

  const handlesubmit = event => {
    // 👇️ prevent page refresh
    event.preventdefault();

    console.log('form submitted ✅');
  };

  return (
    <div><formonsubmit={handlesubmit}><inputtype="text"id="first"name="first"value={first}onchange={event => setfirst(event.target.value)}
        />
        <buttontype="submit">submitbutton>form>div>
  );
};
exportdefaultapp;

we have a button element with its type attribute set to submit in the form.

the form element has a onsubmithandler, so every time the button is clicked or the enter key is pressed, the handlesubmit function is called.

by default, browsers refresh the page when a form submit event is triggered.

we generally want to avoid this in react.js applications because it causes us to lose state.

to prevent the default browser behavior, we must use preventdefault()the method on the event object.

react prevent page refresh on form submit

请注意, even though we used the preventdefault() method, the native browser validation functionality still works as expected.

this is an example of setting the property on an input field required.

import {usestate} from 'react';

const app = () => {
  const [first, setfirst] = usestate('');

  const handlesubmit = event => {
    event.preventdefault();

    console.log('form submitted ✅');
  };

  return (
    <div><formonsubmit={handlesubmit}><inputtype="text"id="first"name="first"value={first}onchange={event => setfirst(event.target.value)}
          required
        />
        <buttontype="submit">submitbutton>form>div>
  );
};
exportdefaultapp;

react native browser validation works

if we need to clear the input value after submitting for , set the state variables to empty string or their respective initial values.

import {usestate} from 'react';

const app = () => {
  const [first, setfirst] = usestate('');

  const handlesubmit = event => {
    event.preventdefault();

    console.log('form submitted ✅');

    // 👇️ clear input field values
    setfirst('');
  };

  return (
    <div><formonsubmit={handlesubmit}><inputtype="text"id="first"name="first"value={first}onchange={event => setfirst(event.target.value)}
        />
        <buttontype="submit">submitbutton>form>div>
  );
};
exportdefaultapp;

previous:

next: none

for reprinting, please send an email to 1244347461@qq.com for approval. after obtaining the author's consent, kindly include the source as a link.

article url:

related articles

publish date:2025/03/07 views:64 category:react

当我们使用 usestate 挂钩声明一个空状态数组但不键入该数组时,会出现错误type is not assignable to type never。 要解决该错误,请使用泛型来键入状态数组,例如 const [arr, setarr] = usestatestr

react error unexpected default export of anonymous function

publish date:2025/03/07 views:61 category:react

unexpected default export of anonymous function警告是在我们尝试使用默认导出导出匿名函数时引起的。 要解决该错误,请在导出之前为函数命名。 下面是一个产生上面错误的示例代码 header.js

ref returns undefined or null in react

publish date:2025/03/07 views:112 category:react

当我们在呈现相应的 dom 元素之前尝试访问其当前属性时,react ref 最常返回 undefined 或 null 。 要解决此问题,需要在 useeffect 钩子中或在触发事件时访问 ref。 import {useref, useeffect} from

passing boolean values as props to components in react

publish date:2025/03/07 views:112 category:react

要将布尔值作为 props 传递给 react 中的组件,请将布尔值包裹在花括号中,例如 child bool={true} / 。 我们传递给组件的所有非字符串类型的道具都必须用大括号括起来。 function child ( {bo

using ref to get the height of an element in react

publish date:2025/03/07 views:195 category:react

在 react 中使用 ref 获取元素的高度: 初始化将存储元素高度的状态变量。 在 useeffect() 挂钩中更新元素的高度。 高度应设置为 ref.current.clientheight 。 import {useeffect, usestate, useref} from re

publish date:2025/03/07 views:133 category:react

在 react 中使用 ref 改变元素的样式: 在元素上设置 ref 属性。 通过 ref 上的 current 属性访问元素。 更新元素的样式,例如 ref.current.style.backgroundcolor = green 。 import {useref} from react ; cons

setting and accessing state with dynamic keys in react

publish date:2025/03/07 views:67 category:react

使用方括号表示法在 react 中使用动态键设置和访问状态,例如 setemployee({...employee, [key]: employee.salary 100}) 。 方括号中的变量或表达式将在设置状态之前进行评估。 import {usestate} from

add an event listener to the body element in react

publish date:2025/03/07 views:131 category:react

向 body 元素添加事件监听器: 访问文档对象上的 body 元素。 在 useeffect 钩子中对 body 元素使用 addeventlistener() 方法。 当组件卸载时移除事件侦听器。 import {useeffect} from react ; export defa

check if an element is in the viewport in react.js

publish date:2025/03/07 views:89 category:react

在 react.js 中检查元素是否在 viewport 中: 在元素上设置 ref 属性。 使用 intersectionobserver api 来跟踪元素是否相交。 app.js import {useeffect, useref, usestate, usememo} from react ; export default function

scan to read all tech tutorials

social media
  • https://www.github.com/onmpw
  • qq:1244347461

recommended

tags

scan the code
easier access tutorial
网站地图