Reputation: 1946
I am trying to trigger the form submit function from custom component
.
In general my goal is to trigger a boolean state value
which is a part of form
, and even though the custom component
is imported inside the form, somehow it doesn't work.
Problem is about sendEmail
function which comes from Custom Component
Here is the codesandbox link and code example below.
Custom Component
import React from "react";
const CustomComponent = (props) => {
return (
<div>
<button onClick={props.sendEmail} type="submit">
send email
</button>
</div>
);
};
export default CustomComponent;
App.js
import { useState } from "react";
import CustomComp from "./CustomComp";
export default function App() {
const [isDone, setIsDone] = useState(false);
const [inputText, setInputText] = useState("");
const handleSubmit = (e) => {
e.preventDefault();
setIsDone(true);
console.log("inputText", inputText);
};
console.log(isDone);
const sendEmail = () => { // this doesn't work
handleSubmit();
console.log("isDone", isDone);
};
const onChangeHandler = (e) => {
setInputText(e.target.value);
};
return (
<form>
<h1>Hello CodeSandbox</h1>
<input type="text" onChange={onChangeHandler} value={inputText} />
<CustomComp sendEmail={sendEmail} />
<button onClick={handleSubmit} type="submit">
submit
</button>
</form>
);
}
Any help will be appreciated
Upvotes: 0
Views: 150
Reputation: 43894
There is no event passed when you trigger it from the custom component so event.preventDefault()
will result in an error.
Add the event to sendMail
, and pass it to handleSubmit
. The onClick
will automatically pass the event as first param:
const handleSubmit = (event) => {
event.preventDefault();
setIsDone(true);
console.log("inputText", inputText);
};
const sendEmail = (event) => {
handleSubmit(event);
console.log("isDone", isDone);
};
Upvotes: 1
Reputation: 618
The first problem you have is you're calling handleSubmit
in the sendEmail
without passing through 'e'
I'd change to this:
const sendEmail = (e) => {
handleSubmit(e);
console.log("isDone", isDone);
};
After doing this, you'll notice your isDone
isn't showing what you'd expect. This is because when you're changing the state via handleSubmit
, it won't change within this call. You shouldn't worry about logging it as you have. It'll only be an issue if you need to do something with the isDone
value
Upvotes: 1