Unable to submit form in Model react - javascript

I have a model file in which I want to submit form but I am not able to trigger submit function my file is like
import React, { useState, useEffect } from "react";
import InputField from "./InputField";
import Button from "./Button";
import axios from "axios";
import { Modal, ModalHeader, ModalBody, ModalFooter } from "reactstrap";
function ArticleOptionsModal(props) {
const [articleOption, setArticleOption] = useState("");
useEffect(() => {
if (typeof props.articleopt === "undefined") {
setArticleOption("");
console.log("hhiii");
} else {
setArticleOption(props.articleopt.optionname);
console.log("hhiii");
}
}, [props]);
return (
<form onSubmit={e => handleSubmit(e)}>
<Modal isOpen={props.modal} toggle={props.toggle}>
<ModalHeader toggle={props.toggle}>Times</ModalHeader>
<ModalBody>
<div className='row'>
<div className='col-sm-6'>
<div className='form-group text-left'>
<label htmlFor='' className='small'>
Name
</label>
<InputField
name='username'
placeholder={"Enter Name"}
value={articleOption.optionname}
onChange={e => changeOptionName(e)}
/>
</div>
</div>
)}
</ModalBody>
<ModalFooter>
<Button
name={"Submit"}
type='submit'
btnLongWidth={false}
onClick={props.toggle}
/>
<Button
name={"Cancel"}
dangerButton={true}
btnLongWidth={false}
onClick={props.toggle}
/>
</ModalFooter>
</Modal>
</form>
);
function changeOptionName(e) {
setArticleOption(e.target.value);
}
function handleSubmit(e) {
console.log("hiiiiii");
}
}
export default ArticleOptionsModal;
Here handleSubmit is not triggering when I try to submit form. I tried using diff methods to just trigger this submit method but till now no luck . Any kind of help would be highly appreciated.

The form tag needs to be inside the modal component as otherwise, the event doesn´t bubble up correctly.
As commented, I would suggest using a form library to handle the form management.
Personally I suggest Final Form:
https://github.com/final-form/react-final-form

Related

Render a new component from the current component after click the button

I am building a login/signup/reset form. I am encountering a problem which is when on the modal of reset password, I would like to click the button to submit email for reset password. After click the button, I want a new success message modal replace the current modal. But the success message always appear below the current reset password modal. How could solve it? Thank you.
Here is the modal component of reset password
import { useState } from "react";
import { updatePasswordFields } from "../constants/formFields";
import FormAction from "./FormAction";
import Input from "./Input";
import MessageContent from "./Message";
const fields = updatePasswordFields;
let fieldsState = {};
fields.forEach((field) => fieldsState[(field.id = "")]);
export default function ForgotPassword() {
const [resetPasswordState, setResetPasswordState] = useState(fieldsState);
const [showMessage, setShowMessage] = useState(false);
const handleChange = (e) =>
setResetPasswordState({
...resetPasswordState,
[e.target.id]: e.target.value,
});
const handleSubmit = (e) => {
e.preventDefault();
setShowMessage(true);
};
return (
<form className="mt-8 space-y-6" onSubmit={handleSubmit}>
<div className="">
{fields.map((field) => (
<>
<label>{field.labelText}</label>
<Input
key={field.id}
handleChange={handleChange}
value={resetPasswordState[field.id]}
labelText={field.labelText}
labelFor={field.labelFor}
id={field.id}
name={field.name}
type={field.type}
isRequired={field.isRequired}
placeholder={field.placeholder}
/>
</>
))}
<FormAction handleSubmit={handleSubmit} text="Update Password" />
{showMessage && <MessageContent />}
</div>
</form>
);
}
Here is the success message modal
import React from "react";
import { MdMarkEmailRead } from "react-icons/md";
export default function MessageContent() {
return (
<div>
<div className="text-sky-600 text-center w-full flex jutify-center">
<MdMarkEmailRead size={44} />
</div>
<div className="text-center text-sm mb-10 max-w-[300px] mx-auto">
We have sent the update password link to your email, please check that!
</div>
</div>
);
}
Here is the result what I got so far screenshot
I'm not sure if I get your means..
If you want to show MessageContent() and hide reset password form in the same modal, there is an easy way to get it.
export default function ForgotPassword() {
// ellipsis...
if (showMessage) {
return <MessageContent />
}
return (
<form ...>...</form>
)
}

Show warning message before unmouting React component

I have a form. I want to show warning before unmounting the form component.
Component is something like this -
import React from "react";
export default function FormComp() {
const sub = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
console.log(formData.get("name"));
//API CALL HERE
};
return (
<div className="test">
<form onSubmit={sub}>
<input name="name" />
<button type="submit">Submit</button>
</form>
</div>
);
}
If the component is unmounted when user goes to a different route, how can i show a warning that form changes will not be saved (along with Yes and No option).As soon as FormComp component is unmounted, form data is cleared.
Are you using react-router? This can be easy with that.
If yes, then you can do something like this:
import { Prompt } from 'react-router'
const FormCompComponent = () => (
<>
<Prompt
when={formIsHalfFilledOut}
message='You have unsaved changes, are you sure you want to leave?'
/>
{/* Component JSX here */}
</>
)
For more details check this out: https://v5.reactrouter.com/core/api/Prompt

React Final Form Error: Must specify either a render prop

I am trying to build a simple form with React-Final-Form like this:
import * as React from "react";
import {
PrimaryButton,
} from "office-ui-fabric-react/lib/Button";
import { Form , Field } from "react-final-form";
import { FORM_ERROR } from "final-form";
import { IUserFormValues } from "../../models/user";
import { RootStoreContext } from "../../stores/rootStore";
import TextInputNew from "./TextInputNew";
const NewUIForm = () => {
const rootStore = React.useContext(RootStoreContext);
const { login } = rootStore.userStore;
return (
<Form
onSubmit={(values: IUserFormValues) =>
login(values).catch((error) => ({
[FORM_ERROR]: error,
}))
}
render={({
handleSubmit,
}) => (
<Form onSubmit={handleSubmit}>
<Field name="email" component={TextInputNew} />
<Field name="email" component={TextInputNew} />
<PrimaryButton type='submit' text="Save" />
</Form>
)}
/>
);
};
export default NewUIForm;
The TextInputNew Component is this:
import * as React from "react";
import { TextField } from "office-ui-fabric-react/lib/TextField";
import { FieldRenderProps } from "react-final-form";
interface IProps extends FieldRenderProps<string, HTMLInputElement> {}
const TextInputNew: React.FC<IProps> = ({ input }) => {
return (
<div>
<input {...input} />
<TextField label="Standard" />
</div>
);
};
export default TextInputNew;
Then I got this error when I use this NewUIForm component
Error: Must specify either a render prop, a render function as children, or a component prop to ReactFinalForm
By the way, the UI framework is Fluent-UI
Can anyone help me? Thanks!!
You're second <Form> should be <form>.
<form onSubmit={handleSubmit}>
<Field name="email" component={TextInputNew} />
<Field name="email" component={TextInputNew} />
<PrimaryButton type='submit' text="Save" />
</form>
To anyone else who might encounter this vague error message, the issue is something going wrong in the render function of <Form>.
For OP, it was using the wrong form tag inside of <Form>.
For me, it was a misspelled property on a <Field> component (components={MyComponent}, oops).
Since the error can be caused by any number of reasons and the message wasn't very specific, one can get an idea of where the problem might be via browser debugger, in my case this is what it looked like:

Modal Not Appearing onClick

I am creating a modal in React that will allow users to add an item to a table. I create a RecipeModal component with a form inside, and I receive no errors when compiling, yet nothing happens when I click the button. I followed a tutorial very closely and have run out of ideas. I've seen people have issues with 'fade' in React that turns the modal completely clear and therefor invisible, but I tried checking in "Inspect" (DevTools? I'm am not sure what it is called) for 'modal' and didn't see it there. I am very new to web developing, so let me know if I should attach something else. I had more input field, but removed them while trying to fix this.
import React, { Component } from 'react';
import { Button, Modal, ModalHeader, ModalBody, Form, FormGroup, Label, Input } from 'reactstrap';
import { connect } from 'react-redux';
import { addRecipe } from '../action/recipeActions';
class RecipeModal extends Component {
state = {
modal: false,
recipe_name: '',
recipe_description: '',
recipe_ingredients: '',
recipe_steps: ''
}
toggle = (e) => {
this.setState({
modal: !this.state.modal
});
}
onChange = (e) => {
this.setState(
{ [e.target.recipe_name]: e.target.value }
);
}
render() {
return (
<div>
<Button
color="dark"
style={{ marginBotton: '2rem' }}
onClick={this.toggle}
>Add Recipe</Button>
<Modal
isOpen={this.state.Modal}
toggle={this.toggle} >
<ModalHeader toggle={this.toggle}>Add a New Recipe</ModalHeader>
<ModalBody>
<Form onSubmit={this.onSubmit}>
<FormGroup>
<Label for="recipe">Recipe</Label>
<Input
type="text"
recipe_name="recipe_name"
id="recipe"
placeholder="Add recipe name"
OnChange={this.onChange} />
</FormGroup>
</Form>
</ModalBody>
</Modal>
</div>
);
}
}
export default connect()(RecipeModal);
State is case-sensitive. So it's either you rename your modal state to Modal
state = {
Modal: false,
...
};
or refactor the isOpen prop to <Modal isOpen={this.state.modal} toggle={this.toggle}>
I suggest the latter.

Hidding a form with onBlur but this have a conflict with submit button

I'm trying to hide the form with the onBlur event, but when I try to click the submit button the onSubmit function doesn't get triggered
I want to hide it after send the form or when the user leaves the div that wraps the form.
https://codesandbox.io/s/rrz10y2mnp
index.js
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
test.ts
import React, { Component } from "react";
export default class Test extends Component {
state = {
showing: false
};
showInput = () => {
this.setState({ showing: false });
};
addNew = () => {
this.setState({ showing: true });
};
sendForm = evt => {
evt.preventDefault();
console.log("clicked");
};
render() {
return (
<div>
{!this.state.showing ? (
<button onClick={this.addNew}>Add a new</button>
) : (
<div onBlur={this.showInput} tabIndex="1">
<form onSubmit={this.sendForm}>
<input autoFocus={true} type="text" />
<button type="submit">PUSH</button>
</form>
</div>
)}
</div>
);
}
}
Hide form in the sendForm function that you have. Then it should be fine. If there is some async function in sendForm you can hideForm when promise gets resolved and till then disable input.
The problem is that your calling setState before the form submits. You could use some async code to fix this issue. Here's a rudimentary example simply using setTimeout and waiting 100 milliseconds. There are better ways to do this and many reasons why you shouldn't.
waitToSetState = () => {
setTimeout(() => {
this.setState({ showing: false });
}, 100);
};
...
<div onBlur={this.waitToSetState} tabIndex="1">
<form onSubmit={this.sendForm}>
<input autoFocus={true} type="text" />
<button type="submit">PUSH</button>
</form>
</div>

Categories

Resources