Reputation: 1131
I'm attempting to render three different components based upon the state stored in hooks.
The state gets sent upon a 'onSubmit' function, which takes the response and if it's successful sets 'submitted' as true, or 'error' as false.
However, when I'm attempting to do conditional rendering, where 'error === true', or 'submitted === true', and then the overall component if neither applies, it's just not showing the component at all.
Can anyone point out what I'm doing wrong here?
Here's my code:
const WaitingListComponent = () => {
const [email, setEmail] = useState('')
const [submitted, setSubmitted] = useState(false)
const [error, setError] = useState(false)
const onSubmit = async (e) => {
e.preventDefault()
await axios.post("/api/waiting-list/addToList", {
email: email
})
.then((response) => {
setSubmitted(true)
})
.catch((err) => {
setError(true)
})
}
const errorComponent = () => {
return (
<form className="waiting-list-component-container" onSubmit={onSubmit}>
<span className="waiting-list-success-span">
<i className="fas fa-times-circle fa-3x waiting-list-error"></i>
<p className="waiting-list-success-paragraph">Oops. Seems like there's been a problem. Please try again.</p>
</span>
</form>
)
}
const successComponent = () => {
return (
<form className="waiting-list-component-container" onSubmit={onSubmit}>
<span className="waiting-list-success-span">
<i className="fas fa-check-circle fa-3x waiting-list-success"></i>
<p className="waiting-list-success-paragraph">Thanks for signing up to our waiting list. A confirmation email is flying your way now.</p>
</span>
</form>
)
}
const form = () => {
return (
<form className="waiting-list-component-container" onSubmit={onSubmit}>
<h4 className="waiting-list-component-heading">Join our waiting list to get early access</h4>
<p className="waiting-list-component-paragraph">Like the sound of us? Join our waiting list to get exclusive early access to our platform when we're ready to launch.</p>
<input className="waiting-list-component-input" name="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" />
<GeneralButton type="submit" text="Get access" />
</form>
)
}
return (
<>
{ error === true ? errorComponent : submitted === true ? successComponent : form }
</>
)
}
Upvotes: 0
Views: 40
Reputation: 442
How about trying this? I think this way may be a little more intuitive.
if (error) return errorComponent();
if (submitted) return successComponent();
return form();
Upvotes: 0
Reputation: 10645
Try this:
return (
<>
{ error ? errorComponent() : submitted ? successComponent() : form() }
</>
)
Upvotes: 1