Home > Blockchain >  How to call onSubmit event from another component on react?
How to call onSubmit event from another component on react?

Time:11-16

I am building a next js application. Unfortunately I have to create two component because design is the critical. Here in one component I have to add form and the another component I have to add submit button. All is good but How can I call onSubmit event from that another component where I put submit button. Please help me.

First component (form component)

import { Box, InputBase } from "@mui/material";
import { useForm } from "react-hook-form";

const OrderPlaced = () => {
    const {
        register,
        handleSubmit,
        formState: { errors }
    } = useForm();
    const onSubmit = (data, e) => {
        console.log(data)
    }
    return (
        <Box component="form" onSubmit={handleSubmit(onSubmit)}>
            <InputBase {...register("name")} />
        </Box>
    );
};
export default OrderPlaced;

And this is the Submit Button Component

import { Box, Button} from "@mui/material";

const SubmitButton= () => {
    return (
        <Box>
            <Button type="submit">Submit Data</Button>
        </Box>
    );
};
export default SubmitButton;

Is there any way to do this. Please help me?

CodePudding user response:

You can think a tricky one. First of all, I can see you are using react-hook-form. Then You must have a common component to call that two component. You should give them also. But No problem. Here I can make one component. Suppose your main component name is App Component.

import { Box } from "@mui/material";
import { useForm } from "react-hook-form";
import OrderPlaced from "./OrderPlaced" // Call OrderPlace component
import SubmitButton from "./SubmitButton" // Call SubmitButton component

const App= () => {
    const {
        register,
        handleSubmit,
        formState: { errors }
    } = useForm();
    const onSubmit = (data, e) => {
        console.log(data)
    }
    return (
        <Box component="form" onSubmit={handleSubmit(onSubmit)}>
            <OrderPlaced register={register} />
            <SubmitButton />
        </Box>
    );
};
export default App;

Here in App component we should use reack-hook-form . We can pass register to any component as props. This is the tricks. Just you should call the SubmitButton component Inside the form tag. Just it.

Then your OrderPlaced component will be-

import { Box, InputBase } from "@mui/material";

const OrderPlaced = ({register}) => {
    return (
        <Box>
            <InputBase {...register("name")} />
        </Box>
    );
};
export default OrderPlaced;

Now You can use register to any component. Just pass the props. You have not to change SubmitButton Component. That's it. You can go through in that way as you are using react-hook-form. Thank you..

  • Related