Comments (14)
Hi, @mayank1513 can you try the code I have mentioned below , I think it will solve your problem and let me know if there is anything wrong.
`export default function App() {
const [clicked, setClicked] = useState(false);
return (
<form
onSubmit={(e) => {
e.preventDefault();
console.log("form submitted!");
}}
>
{!clicked ? (
<button type="submit" onClick={() => setClicked(true)}>
"button"
) : (
<button type="button" onClick={() => setClicked(false)}>
"submit"
)}
);
}`
from react.
Hi, why are you tagging type="submit" as "button" and vice-versa? These values are used to demonstrate the current working and understand why it is working this way.
from react.
Action corresponding to the button which I click should be triggered. Not the other button.
from react.
This behavior that you are seeing is because the form's onSubmit event is triggered regardless of the button type always.... Maybe you should move your state modifiers outside the buttons
Try this
import { useState } from "react";
export default function App() {
const [clicked, setClicked] = useState(false);
const handleFormSubmit = (e) => {
e.preventDefault();
if (clicked) {
setClicked(false)
console.log('form submitted!');
// Perform other necessary actions
} else {
setClicked(true)
}
};
return (
<form>
{!clicked ? (
<button type="button" onClick={(e)=>handleFormSubmit(e)}>
Type "button"
</button>
) : (
<button type="submit" onClick={(e)=>handleFormSubmit(e)}>
Type "submit"
</button>
)}
</form>
);
}
You can also use e.target.form.submit
inside the handler to in fact submit the form.
from react.
Please check the code sandbox carefully. Event is triggered only for one type of button, not both. You can even verify this by removing the condition and rendering both buttons together.
from react.
I changed code and add a preventDefault to button
import { useState } from "react";
export default function App() {
const [clicked, setClicked] = useState(false);
return (
<form
onSubmit={(e) => {
e.preventDefault();
setClicked(true);
console.log("form submitted!");
}}
>
{!clicked ? (
<button type="submit">Type "submit"</button>
) : (
<button
type="button"
onClick={(e) => {
e.preventDefault();
setClicked(false);
}}
>
Type "button"
</button>
)}
</form>
);
}
from react.
Greetings @mayank1513 Here is the modified code.
import { useState } from "react";
export default function App() {
const [clicked, setClicked] = useState(false);
return (
<form
onSubmit={(e) => {
e.preventDefault();
console.log("form submitted!");
}}
>
{!clicked ? (
<button
type="button"
onClick={() => {
const timer = setTimeout(() => {
setClicked(true);
clearTimeout(timer);
}, 0);
}}
>
Type "button"
) : (
<button
type="submit"
onClick={() => {
const timer = setTimeout(() => {
setClicked(false);
clearTimeout(timer);
}, 0);
}}
>
Type "submit"
)}
);
}
The issue was that React updates the virtual dom faster than the real dom. So we must add the async behaviour to the onClick event where the state is being changed.
from react.
from react.
To resolve it, I assigned each button unique key
prop. Hope this helped solve the problem
from react.
To resolve it, I assigned each button unique
key
prop. Hope this helped solve the problem
After assigning a unique key, the form-submit event is not fired at all.
from react.
so can you explain why this unususal behaviour was happening? I mean when we are clicking "type= button" button the onSubmit event was triggering.
from react.
I changed code and add a preventDefault to button
import { useState } from "react"; export default function App() { const [clicked, setClicked] = useState(false); return ( <form onSubmit={(e) => { e.preventDefault(); setClicked(true); console.log("form submitted!"); }} > {!clicked ? ( <button type="submit">Type "submit"</button> ) : ( <button type="button" onClick={(e) => { e.preventDefault(); setClicked(false); }} > Type "button" </button> )} </form> ); }
This does not address the issue.
from react.
import { useState } from "react";
export default function App() {
const [clicked, setClicked] = useState(true);
return (
<form
onSubmit={(e) => {
e.preventDefault();
console.log("form submitted!");
}}
>
{clicked && (
<button type="submit" onClick={() => setClicked(false)}>
Type "submit"
</button>
)}
<button type="submit" onClick={() => setClicked(true)}>
Type "submit 2"
</button>
</form>
);
}
i believe when state change from false to true it will immediately remove Type "submit" button and it will also clean pending effects like form submit check above code
- conditional rendering and without conditional rendering
from react.
Greetings @mayank1513 Here is the modified code.
import { useState } from "react"; export default function App() { const [clicked, setClicked] = useState(false); return ( <form onSubmit={(e) => { e.preventDefault(); console.log("form submitted!"); }} > {!clicked ? ( <button type="button" onClick={() => { const timer = setTimeout(() => { setClicked(true); clearTimeout(timer); }, 0); }} > Type "button" ) : ( <button type="submit" onClick={() => { const timer = setTimeout(() => { setClicked(false); clearTimeout(timer); }, 0); }} > Type "submit" )} ); }
The issue was that React updates the virtual dom faster than the real dom. So we must add the async behaviour to the onClick event where the state is being changed.
This is not the expected behavior. Moreover, when you add unique keys to buttons, none of them submit. We are not looking for workarounds, but trying to improve React library itself to handle this gracefully.
from react.
Related Issues (20)
- Bug: Nested suspense boundaries `Cannot read properties of null (reading 'parentNode')` on resolution HOT 2
- Bug: pending attribute from useFormStatus is stuck as "true" when form action takes longer than ~5s to resolve HOT 6
- React developer tools messes with Smartermail HOT 1
- Bug: Unable to build react repo locally in Mac HOT 2
- Bug: Select when passed a value as Prop errors with a suggestion to pass readOnly HOT 16
- Bug: Seems like new hydrateRoot method doesn't provide any promise or callback to catch hydration process finish HOT 2
- Bug: react-hooks/exhaustive-deps doesn't detect unnecessary dependencies HOT 3
- Bug: New Suspense boundaries not shown until existing Suspense boundaries have resolved during transition HOT 1
- Bug: You prioritized Nextjs. I have two questions... HOT 3
- Bug: useReducer triggers reducer one more time in React 18 Responsive Mode HOT 12
- Bug: setState does not work, in the custom hook in the Safari browser HOT 1
- Feature Request: Support the `defaultSelected` Property for Rendered `<option>` Elements HOT 7
- Bug: useSyncExternalStore does not schedule update after mutation HOT 8
- TrustedTypes broken when using react HOT 3
- Bug: When building by UMD, react bundle does not includes Scheduler HOT 4
- Doc's Demo that includes const theme = use(ThemeContext) is broken HOT 4
- Bug: Difference of state behaviour between function components and class components HOT 6
- Bug: After kills the app, the cleanup function in useEffect does not execute? HOT 4
- Please, please the development of React Class Components HOT 1
- Bug: Components rendered in React.Suspense can't have their size reliably measured HOT 2
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from react.