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
handleSubmit()which means thatewill be undefined. Soe.preventDefault()causes a crash. I'm confused on what your goal is and why you have more than one submit button but you can eliminate the crash by moving the form submit logic into another function and calling that instead of callinghandleSubmitwith no arguments