I am trying to create a hook that hides my form after it has been submitted whilst trying to show the message sent image afterwards, but I can’t seem to get the form
to disappear.
so far I have tried this:
const ContactForm = () => {
...
const [show, setShow] = React.useState(true);
const handleSubmit = (e) => {
...
}
My content is here:
return (
<>
{show ? (
<form onSubmit={handleSubmit} className='email-form'>
<div className='form'>
<input .../>
<input .../>
<textarea .../>
</div>
<button
disabled={!name || !email || !message}
onClick={() => {
handleSubmit();
setShow(!show);
if(!handleSubmit) {
setShow(false)
} else {
setShow(true)
}
}}
type="submit"
className='send-btn'
>
<span>Send Message</span>
</button>
<div className='message-sent'>
<CircleCheckBig className='sent-tick' strokeWidth={1} size={200}/>
<p className='sent-message'>Message Sent</p>
</div>
</form>) : null}
</>
I want the 'email-form'
to disappear when the ‘Send Message’ button is clicked and to be replaced with the message-sent
<div>
. Any ideas on how to achieve this?
I tried an if statement and hooks mainly.
2
Answers
Get rid of this code entirely:
You’ve defined
handleSubmit
as a function, so interpreting it as a boolean (1) makes no sense and (2) will always be truthy (which you negate tofalse
). Since the result is always the same, you’re always invoking theelse
block and always settingshow
totrue
.Since the two lines of code before this structure already:
Then you don’t need the rest of this structure anyway. It’s not clear where you got this or what you expect it to do and why. But what is is doing is explicitly always setting
show
totrue
.Currently both the
<form>
and the<div>
are either both shown or both not shown, because they’re both in the same part of your ternary conditional expression:Separate them. Specifically, make them the two different results of your ternary conditional expression:
That way you’re showing one or the other, not both or neither.
Your mistake is that your div, where your message is at, is inside the form tag. You have to move it outside and replace it with
null
:Furthermore your
onClick
function inside your button is a bit "weird". What you are trying to achieve is that you only want the message inside the div to be seen, if the button was pressed by checking ifhandleSubmit
was called. I would rather delete the wholeonClick
functionality and move thesetShow(true)
to thehandleSubmit
function. Because if you click on the button, theonSubmit
event is called inside the form automatically (this is because by standard the HTML button is from typesubmit
.) So you can do it like this: