Whats wrong with this Form , when i click submit button the signInSubmitHandler() function is not called , i tested it with a simple Button with onClick and it works but if i use Form with submit button it doesnt work. (im using reactjs)
in SignInForm.jsx file:
const SignInForm = (props) => {
return (
<React.Fragment>
<h1>Welcome to ToDo</h1>
<form onSubmit={props.signInSubmitHandler} className={style.signInForm}>
<div className={style.signInFormImportantElements}>
<span className={style.userFormsErrors}>{props.userEmailError}</span>
<input
name="userEmail"
type="email"
placeholder="email"
value={props.currentUserEmailText}
className={style.signInText}
onChange={(e) => {
props.signInOnChangeHandler(e);
}}
onBlur={(e) => props.signInOnBlurHandler(e)}
/>
<span className={style.userFormsErrors}>{props.userPasswordError}</span>
<input
name="userPassword"
type="password"
placeholder="password"
value={props.currentUserPasswordText}
className={style.signInText}
onChange={(e) => {
props.signInOnChangeHandler(e);
}}
onBlur={(e) => props.signInOnBlurHandler(e)}
/>
<input type="submit" value="Submit" className={style.signInSubmit} />
</div>
<div className={style.signInLinks}>
Forget Password
Create Account
</div>
</form>
</React.Fragment>
);
};
in app.jsx file :
signInSubmitHandler() {
console.log('waaaat');
}
Form Code image
props
signInSubmitHandler binding
signInSubmitHandler function
your function has one param
signInSubmitHandler(e) {
console.log('waaaat');
}
so try this
<form onSubmit={(e) => props.signInSubmitHandler(e)} className={style.signInForm}>
Related
i want to validate my form by checking if all the fields are filled. I am quite new to react. Any suggestions? I have got the states ready, but i am pretty much stuck. Thank you in advance for your replies. I appreciate it
my code:
const [fields, setFields] = useState({
name: '',
email: '',
subject: '',
msg: '',
});
const handleSubmit = (event) => {
emailjs.sendForm().then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
alert('form submitted');
event.target.reset();
event.preventDefault();
};
<form onSubmit={handleSubmit}>
<div className={styles.firstInputs}>
<div>
<label>name</label>
<br />
<input
type='text'
refs='name'
name='name'
placeholder='your name'
></input>
</div>
<div>
<label>email</label>
<br />
<input type='email' name='email' placeholder='email'></input>
</div>
</div>
<label>subject</label>
<br />
<input
type='text'
name='subject'
placeholder='subject'
className={styles.subject}
></input>{' '}
<br />
<label>message</label> <br />
<textarea placeholder='your message' name='message'></textarea>
<br />
<button type='submit' className={styles.sendForm}>
SUBMIT
</button>
</form>;
You are not using your state correctly there.
Set the values of the fields to what is in the state, then change the state when the fields change.
Don't forget you can just add the required attribute to your HTML element to make sure it gets some kind of value.
Then you just validate the state before submission.
Don't just fall back on packages all the time as people suggest here. As you say, you are new to React so, learn to set things up manually (which is basically less work for small forms). Once you understand that, then consider if having another dependency is really saving you time.
See sample code below in action here: https://codesandbox.io/s/form-validation-pbbf1
import { useState } from "react";
import "./styles.css";
const defaultFields = { name: "", email: "", subject: "", message: "" };
export default function App() {
const [fields, setFields] = useState(defaultFields);
const handleSubmit = (event) => {
// Stop form from resetting
event.preventDefault();
// Check fields
if (fields.name.length < 2) {
return alert("Name should be greater than 1 character.");
}
// etc...
// Send off data
/*
emailjs.sendForm().then(
(result) => {
console.log(result.text);
},
(error) => {
console.log(error.text);
}
);
*/
// I would probably put these two
// lines inside the then block above.
setFields(defaultFields);
alert("form submitted");
};
const handleFieldChange = (e) => {
const { name, value } = e.target;
setFields((previousFields) => ({ ...previousFields, [name]: value }));
};
return (
<form onSubmit={handleSubmit}>
{/* NAME */}
<div>
<label>name</label>
<br />
<input
type="text"
name="name"
placeholder="your name"
value={fields.name}
required
onChange={handleFieldChange}
></input>
</div>
{/* EMAIL */}
<div>
<label>email</label>
<br />
<input
type="email"
name="email"
placeholder="email"
value={fields.email}
required
onChange={handleFieldChange}
></input>
</div>
{/* SUBJECT */}
<div>
<label>subject</label>
<br />
<input
type="text"
name="subject"
placeholder="subject"
value={fields.subject}
required
onChange={handleFieldChange}
></input>{" "}
<br />
</div>
{/* MESSAGE */}
<div>
<label>message</label> <br />
<textarea
placeholder="your message"
name="message"
value={fields.message}
required
onChange={handleFieldChange}
></textarea>
</div>
<button type="submit">SUBMIT</button>
</form>
);
}
I am developing a chat and the problem I am having has to do with creating a new chat. When clicking on the button to create a new chat, a popup appears with the chat name field to fill in. However, when I click on "Create Now" I can't get the input text.
I've tried adding value = {nameChat} but this way I can't write to the input. Nothing appears. I also tested defaultValue = {nameChat} but it doesn't work either.
If anyone could help me, I would appreciate it.
Popup to create new chat
import { confirmAlert } from 'react-confirm-alert'; // Import
import 'react-confirm-alert/src/react-confirm-alert.css' // Import css
import { useState } from 'react'
const HeaderChats = ({ onAddNewChat }) => {
var [chatName, setChatName] = useState('');
const onSubmit = (e) => {
e.preventDefault()
if (!chatName) {
alert('Please write the name of the chat!')
console.log("Nome -> " + chatName)
return
}
console.log(chatName)
onAddNewChat(chatName)
setChatName('')
}
function createChat() {
confirmAlert({
customUI: ({ onClose }) => {
return (
<div className='custom-ui'>
<h1>Create new chat</h1>
<form style={{resize: "vertical"}} onSubmit={onSubmit}>
<label className="cname-label">Chat Name</label>
<input className="cname-input" type='text' placeholder="Type the name of the chat..." onChange={(e) => setChatName(e.target.value)} value={chatName}/>
<button className="cancel-button" onClick={onClose}>Cancel</button>
<button className="submit-new-chat-button" type='submit'>Create now</button>
</form>
</div>
)
}
})
}
return (
<div className="header-left">
<div className="header-left-column-left">
<HiMenu className="icon" size={25} style={{ color: "#b3c5d3" }} />
</div>
<div className="header-left-column-right">
<input className="input-search" type="text" placeholder="Pesquisar conversa..." />
<MdAddCircleOutline className="button-new-message" size={25} style={{ color: "#dca297" }} onClick={() => createChat()} /> </div>
</div>
);
}
Because once the confirmAlert is created, the submit function will not be changed. So to avoid this, you need to render the chat as a component.
function Chat(props){
var [chatName, setChatName] = useState("");
const onSubmit = useCallback((e) => {
e.preventDefault();
if (!chatName) {
alert("Please write the name of the chat!");
return;
}
alert(chatName);
setChatName("");
}, [chatName]);
return <div className="custom-ui">
<h1>Create new chat</h1>
<form style={{ resize: "vertical" }} onSubmit={onSubmit}>
<label className="cname-label">Chat Name</label>
<input
className="cname-input"
type="text"
placeholder="Type the name of the chat..."
onChange={(e) => setChatName(e.target.value)}
/>
<button className="cancel-button" onClick={props.onClose}>
Cancel
</button>
<button className="submit-new-chat-button" type="submit">
Create now
</button>
</form>
</div>
}
function App() {
function createChat() {
confirmAlert({
customUI: ({ onClose }) => {
return (
<Chat onClose={onClose}/>
);
}
});
}
return (
<div className="header-left">
<MdAddCircleOutline
className="button-new-message"
size={25}
style={{ color: "#dca297" }}
onClick={() => createChat()}
/>{" "}
</div>
);
}
You should remove onSubmit in form element and also remove type="submit" on button change it to onClick={onSubmit}
<div className="custom-ui">
<h1>Create new chat</h1>
<form style={{ resize: "vertical" }} >
<label className="cname-label">Chat Name</label>
<input
className="cname-input"
type="text"
placeholder="Type the name of the chat..."
onChange={(e) =>
{
setChatName(e.currentTarget.value)}
}
/>
<button className="cancel-button" onClick={onClose}>
Cancel
</button>
<button className="submit-new-chat-button" onClick={onSubmit}>
Create now
</button>
</form>
</div>
I'm using formik in a reactjs project, and I want to use Prompt from react-router to open a notification before a user leaves and loses changes made to their submission.
I'd expected something like this to work:
<Prompt
when={formik.dirty}
message="You have unsaved changes. Are you sure you want to leave?"
/>
My formik block looks like this:
const formik = useFormik({
initialValues: {
<values>
},
enableReinitialize: true,
validate,
onSubmit: values => {
<submit functional stuff>
}
});
And my form is something like this:
<form id="myForm" onSubmit={formik.handleSubmit}>
<div className="row">
<div className="form-group">
<label htmlFor="name">Name</label>
<input
id="name"
type="text"
onChange={formik.handleChange}
value={formik.values.name}
className="form-control"
placeholder="Enter name"
disabled={isDisabled}
/>
{formik.errors.name ? <div className="text-danger">{formik.errors.name}</div> : null}
</div>
<div className="form-group">
<label htmlFor="subject">Subject</label>
<input
id="subject"
type="text"
onChange={formik.handleChange}
value={formik.values.subject}
className="form-control"
placeholder="Email subject"
disabled={isDisabled}
/>
{formik.errors.subject ? <div className="text-danger">{formik.errors.subject}</div> : null}
</div>
</div>
</form>
but it appears that formik.dirty is either not defined or it's not seen as true (despite making changes to the form).
How would I properly use the dirty prop to trigger the Prompt?
I am not sure what kind of setup you have, but I created a PoC with routing which has two tabs (links) for navigation and I am using prompt on tab with formik form component.
import React from "react";
import { Prompt } from "react-router-dom";
import { useFormik } from "formik";
const MyForm = () => {
const formik = useFormik({
initialValues: {
name: "",
subject: ""
},
enableReinitialize: true,
onSubmit: (values) => {
alert(JSON.stringify(values, null, 2));
},
onChange: (e) => {
console.log(e);
}
});
return (
<div>
<Prompt
when={!!formik.dirty}
message={(location) =>
`Are you sure you want to go to ${location.pathname}`
}
/>
<form id="myForm" onSubmit={formik.handleSubmit}>
<div className="row">
<div className="form-group">
<label htmlFor="name">Name</label>
<input
id="name"
type="text"
onChange={formik.handleChange}
value={formik.values.name}
className="form-control"
placeholder="Enter name"
/>
{formik.errors.name ? (
<div className="text-danger">{formik.errors.name}</div>
) : null}
</div>
<div className="form-group">
<label htmlFor="subject">Subject</label>
<input
id="subject"
type="text"
onChange={formik.handleChange}
value={formik.values.subject}
className="form-control"
placeholder="Email subject"
/>
{formik.errors.subject ? (
<div className="text-danger">{formik.errors.subject}</div>
) : null}
</div>
{formik.dirty && <button tye="submit">Save</button>}
</div>
</form>
</div>
);
};
export default MyForm;
take a look the this codesandbox.
const sendMessage = async (event) => {
event.preventDefault();
<div className="chat_footer">
<InsertEmoticonIcon />
<form>
<input value={input} onChange={(e) => setInput(e.target.value)} placeholder="Type a message" type="text" />
<button onclick={sendMessage} type="submit">
Send a message
</button>
</form>
<MicIcon />
</div>
prevent default is not working keeps refreshing the webpage and sendMessage is not working as well
sendMessage, should be passed to onSubmit handler of the form element, as below.
const sendMessage = async (event) => {
event.preventDefault();
<div className="chat_footer">
<InsertEmoticonIcon/>
<form onSubmit={sendMessage}>
<input
value={input} onChange={e => setInput(e.target.value)}
placeholder="Type a message"
type="text"
/>
<button type="submit">
Send a message
</button>
</form>
<MicIcon/>
</div>
I've been trying to console.log these 2 inputs, but can't seem to figure it out, can anyone tell me what I've done wrong?
I keep getting the Cannot read property 'value' of null error
function printInputs() {
let username = document.getElementById('user').value
let password = document.getElementById('pass').value
console.log(username);
console.log(password);
}
function App() {
return (
<div className="App">
<h1>Log In</h1>
<h1>{code}</h1>
<form>
<input className='userInput' id='user' type='text' placeholder='username' /><br />
<input className='userInput' id='pass' type='password' placeholder='password' /><br />
<input className='userSubmit' type='submit' value='Log In' onSubmit={printInputs()} />
</form>
</div>
);
}
onSubmit={printInputs()}
You are trying to call printInputs immediately (before the render function has returned anything so before the inputs are in the page).
You need to pass a function to onSubmit:
onSubmit={printInputs}
That said, this is not the approach to take for getting data from forms in React. See the Forms section of the React guide for the right approach.
The way to write forms in react. Working example demo
function App() {
const [state, setState] = React.useState({ username: "", password: "" });
const handleSubmit = e => {
e.preventDefault();
console.log(state);
};
const handleChange = e => {
setState({
...state,
[e.target.name]: e.target.value
});
};
return (
<div className="App">
<h1>Log In</h1>
<form onSubmit={handleSubmit}>
<input
className="userInput"
name="username"
type="text"
placeholder="username"
onChange={handleChange}
/>
<br />
<input
className="userInput"
name="password"
type="password"
placeholder="password"
onChange={handleChange}
/>
<br />
<input className="userSubmit" type="submit" value="Log In" />
</form>
</div>
);
}
in the first never use real dom to manipulate the dom in
React ,use a state to get de value and the onSumbit is used in Form tag
import React, { useState } from "React";
const App = () => {
const [userName, setUserName] = useState("");
const [password, setPassword] = useState("");
const printInputs = () => {
console.log(userName);
console.log(password);
};
return (
<div className="App">
<h1>Log In</h1>
<form onSubmit={printInputs}>
<input
className="userInput"
id="user"
type="text"
placeholder="username"
onChange={event => setUserName(event.target.value)}
/>
<br />
<input
className="userInput"
id="pass"
type="password"
placeholder="password"
onChange={event => setPassword(event.target.value)}
/>
<br />
<input
className="userSubmit"
type="submit"
value="Log In"/>
</form>
</div>
);
};
export default App;