event.preventDefault( ) is NOT working in React - reactjs

Unable to get values in console!
What am I doing it incorrectly?
Attached below is the functional component of React
The Handler Functions
import React, { useState, useRef } from 'react';
const SimpleInput = (props) => {
const nameInputRef = useRef();
const [enteredName, setEnteredName] = useState('');
const nameInputChangeHandler = (event) => {
setEnteredName(event.target.value);
};
const formSubmissionHandler = (event) => {
event.preventDefault();
console.log(enteredName);
const enteredName = nameInputRef.current.value;
console.log(enteredName);
};
return (
<form>
<div className="form-control" onSubmit={formSubmissionHandler}>
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);
};
export default SimpleInput;

formSubmissionHandler should have on the form element rather than the div element.
return (
<form onSubmit={formSubmissionHandler}>
<div className="form-control">
<label htmlFor="name">Your Name</label>
<input
ref={nameInputRef}
type="text"
id="name"
onChange={nameInputChangeHandler}
/>
</div>
<div className="form-actions">
<button>Submit</button>
</div>
</form>
);

Related

Problem in communicating props in reactjs

I am not getting the choosen program option to select user,The props supposed to communicate from program.js to enrollmentform can anyone help me figuring out why the choosen program is not appearing
the code is --:
My App.js Code is ---:
import './App.css';
import EnrollmentForm from './EnrollmentForm';
function App() {
return (
<div className="App">
<EnrollmentForm >Just React</EnrollmentForm>
</div>
);
}
export default App;
My enrollmentform.js code is ---:
import { useState } from "react";
import "./App.css";
function EnrolmentForm(props) {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [welcomeMessage, setWelcomeMessage] = useState("");
const handleSubmit = (event) => {
setWelcomeMessage(`Welcome ${firstName} ${lastName}`);
event.preventDefault();
};
return (
<div>
<form className="enrolForm" onSubmit={handleSubmit}>
<h1>{props.chosenProgram} Student Details</h1>
<label>First name:</label>
<input
type="text"
name="fname"
onBlur={(event) => setFirstName(event.target.value)}
/>
<br />
<label>Last name:</label>
<input
type="text"
name="lname"
onBlur={(event) => setLastName(event.target.value)}
/>
<br />
<br />
<input type="submit" value="Submit" />
<br />
<label id="studentMsg" className="message">
{welcomeMessage}
</label>
</form>
</div>
);
}
export default EnrolmentForm;
my program.js code is ---:
import "./App.css";
import EnrolmentForm from "./EnrolmentForm";
import { useState } from "react";
function App() {
const [program, setProgram] = useState("UG");
const handleChange = (event) => {
setProgram(event.target.textContent);
};
return (
<div className="App">
<div className="programs">
<label>Choose Program:</label>
<select className="appDropDowns"
onChange={handleChange}
value={program} >
<option value="UG">Undergraduate</option>
<option value="PG">Postgraduate</option>
</select>
</div>
<EnrolmentForm chosenProgram={program} />
</div>
);
}
The desired output supposed to be--->
and the output which I am getting
There supposed to be a option of choosen program but it is not working and not apearing when I run the code
Your Code Should Look like This:
In App.js:
import './App.css';
import Program from './Program';
function App() {
return (
<div className="App">
<Program />
</div>
);
}
export default App;
In Enrollment.js code:
import { useState } from "react";
import "./App.css";
function EnrolmentForm(props) {
const [firstName, setFirstName] = useState("");
const [lastName, setLastName] = useState("");
const [welcomeMessage, setWelcomeMessage] = useState("");
const handleSubmit = (event) => {
setWelcomeMessage(`Welcome ${firstName} ${lastName}`);
event.preventDefault();
};
return (
<div>
<form className="enrolForm" onSubmit={handleSubmit}>
<h1>{props.chosenProgram} Student Details</h1>
<label>First name:</label>
<input
type="text"
name="fname"
onBlur={(event) => setFirstName(event.target.value)}
/>
<br />
<label>Last name:</label>
<input
type="text"
name="lname"
onBlur={(event) => setLastName(event.target.value)}
/>
<br />
<br />
<input type="submit" value="Submit" />
<br />
<label id="studentMsg" className="message">
{welcomeMessage}
</label>
</form>
</div>
);
}
export default EnrolmentForm;
And Program.js code:
import { useState } from "react";
import "./App.css";
import EnrolmentForm from "./EnrolmentForm";
function Program() {
const [program, setProgram] = useState("UG");
const handleChange = (event) => {
setProgram(event.target.textContent);
};
return (
<div className="App">
<div className="programs">
<label>Choose Program:</label>
<select
className="appDropDowns"
onChange={handleChange}
value={program}
>
<option value="UG">Undergraduate</option>
<option value="PG">Postgraduate</option>
</select>
</div>
<EnrolmentForm chosenProgram={program} />
</div>
);
}
export default Program;

Pass data from a form component to another component in react hook

I have the following form, and I need that when submitting the form, its information is displayed in a new component.
Perhaps the issue of redirecting to the other component could be done by creating a route. But I don't know how said component obtains the information of the form
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
import {useState, useRef} from 'React'
export default const FormX = () => {
const [formValues, setFormValues] = useState({
name: "",
priceUnitary: "",
size: "",
description: "",
});
const inputFileRef = useRef();
const handleChange = (event) => {
const { name, value } = event.target;
console.log(name, value);
setFormValues({ ...formValues, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formValues);
console.log(inputFileRef.current.files);
};
return (
<>
<form id="formu" onSubmit={handleSubmit} className="row">
<h1>FORM SEND</h1>
<div className="col-md-6">
<label>Name</label>
<input
placeholder="Text input"
name="name"
value={formValues.name}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Size</label>
<input
type="number"
placeholder="Text input"
name="size"
value={formValues.size}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Price Unitary</label>
<input
type="number"
placeholder="Text input"
name="priceUnitary"
value={formValues.priceUnitary}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Description</label>
<input
placeholder="Text input"
name="description"
value={formValues.description}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>File / Image</label>
<input type="file" ref={inputFileRef} />
</div>
<button type="submit" className="color-primary">
Save
</button>
</form>
</>
);
};
Link:
https://codesandbox.io/s/send-form-dcj5v?file=/src/App.js
You can hide your form by change your state on form sumbit and display another component. You have to pass formValue as props in View component. Now think you have better idea what you have to do...
Here i added new component, that display form value on submit
App.js
import { useState, useRef } from "react";
import View from "./View";
const FormX = () => {
const [formValues, setFormValues] = useState({
name: "",
priceUnitary: "",
size: "",
description: ""
});
const [isFormVisible, setIsFormVisible] = useState(true);
const inputFileRef = useRef();
const handleChange = (event) => {
const { name, value } = event.target;
console.log(name, value);
setFormValues({ ...formValues, [name]: value });
};
const handleSubmit = (e) => {
e.preventDefault();
console.log(formValues);
console.log(inputFileRef?.current?.files);
setIsFormVisible(false);
};
return (
<>
{isFormVisible ? (
<form id="formu" onSubmit={handleSubmit} className="row">
<h1>FORM SEND</h1>
<div className="col-md-6">
<label>Name</label>
<input
placeholder="Text input"
name="name"
value={formValues?.name}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Size</label>
<input
type="number"
placeholder="Text input"
name="size"
value={formValues.size}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Price Unitary</label>
<input
type="number"
placeholder="Text input"
name="priceUnitary"
value={formValues.priceUnitary}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>Description</label>
<input
placeholder="Text input"
name="description"
value={formValues.description}
onChange={handleChange}
/>
</div>
<div className="col-md-6">
<label>File / Image</label>
<input type="file" ref={inputFileRef} />
</div>
<button type="submit" className="color-primary">
Save
</button>
</form>
) : (
<View data={formValues} />
)}
</>
);
};
export default FormX;
View.js
import React from "react";
const View = ({ data }) => {
return (
<div>
<p>Name: {data?.name}</p>
<p>priceUnitary: {data?.priceUnitary}</p>
<p>description: {data?.description}</p>
</div>
);
};
export default View;

Submit Form Using React Redux

I am using react-redux hooks.I want to dispatch an action after some validations when the form is submitted. But I cannot call usedispatch() hook outside function component. Is there any way I can dispatch an action using usedispatch() ?
My code looks as below:
import React, { Component } from 'react';
import { register } from '../../actions/auth';
import { useDispatch, useSelector } from "react-redux";
let state = {
username: '',
password1: '',
password2: '',
}
const onSubmit = (e) => {
e.preventDefault()
const dispatch = useDispatch();
if (state.password1 === state.password2) {
dispatch(register(state))
}
else {
console.log('Psw did not matched.')
}
}
const onChange = (e) => {
let field_name = e.target.name;
state[field_name] = e.target.value;
}
const Register = () => {
return (
<div className="col-md-6 m-auto">
<div className="card card-body mt-5">
<h2 className="text-center">Register</h2>
<form encType="multipart/form-data" onSubmit={onSubmit}>
<div className="form-group">
<label>Username</label>
<input
type="text"
className="form-control"
name="username"
onChange={onChange}
required/>
</div>
<div className="form-group">
<label> Password</label>
<input
type="password"
className="form-control"
name="password1"
onChange={onChange}
required/>
</div>
<div className="form-group">
<label>Confirm Password</label>
<input
type="password"
className="form-control"
name="password2"
onChange={onChange}
required/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
);
}
export default Register;
I get an error that React Hooks cannot be used outside function component and it is obvious. I am looking for a way to dispatch register action after doing some validation when form is submitted.
Since you are writing a React component, it would make sense if you define your state within and other functions within the component. This way you would be able to use hook, useDispatch as well. Also you can make your input fields controlled instead of letting them be uncontrolled
import React, { Component } from 'react';
import { register } from '../../actions/auth';
import { useDispatch, useSelector } from "react-redux";
const Register = () => {
const [state, setState] = useState({
username: '',
password1: '',
password2: '',
});
const onChange = (e) => {
let field_name = e.target.name;
let field_value = e.target.value;
setState(prev => ({...prev, [field_name]: field_value});
}
const dispatch = useDispatch();
const onSubmit = (e) => {
e.preventDefault()
if (state.password1 === state.password2) {
dispatch(register(state))
}
else {
console.log('Psw did not matched.')
}
}
return (
<div className="col-md-6 m-auto">
<div className="card card-body mt-5">
<h2 className="text-center">Register</h2>
<form encType="multipart/form-data" onSubmit={onSubmit}>
<div className="form-group">
<label>Username</label>
<input
type="text"
className="form-control"
name="username"
value={state.username}
onChange={onChange}
required/>
</div>
<div className="form-group">
<label> Password</label>
<input
type="password"
className="form-control"
name="password1"
value={state.password1}
onChange={onChange}
required/>
</div>
<div className="form-group">
<label>Confirm Password</label>
<input
type="password"
className="form-control"
name="password2"
value={state.password2}
onChange={onChange}
required/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">Register</button>
</div>
</form>
</div>
</div>
);
}
export default Register;

How to do routing by using Conditions in React

I am working on a React project, First I have to Signup then I stored Signup details in local storage so when I came to login screen after entering email and password and when I click submit button then it has to check the email and password from local storage. So if both are same then it should redirects to another page, I am trying to do this but it is showing some error so someone please help me to resolve this error
This is my code
This is Signup.js
import React, { useState, useRef } from 'react';
import './Signup.css';
const Signup = () => {
const [data, sendData] = useState({})
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
sendData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
localStorage.setItem('userInfo', JSON.stringify(data))
}
const myForm = useRef(null)
const resetForm = () => {
myForm.current.reset();
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='registerForm'>
<form onSubmit={handleSubmit} ref={myForm}>
<div className="form-group mb-2">
<label htmlFor="firstname">Firstname</label>
<input type="text" className="form-control" onChange={handleChange} name='firstname' id="firstname" placeholder="Enter firstname"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="lastname">Lastname</label>
<input type="text" className="form-control" onChange={handleChange} name='lastname' id="lastname" placeholder="Enter lastname"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="email">Email</label>
<input type="email" className="form-control" onChange={handleChange} name='email' id="email" placeholder="Enter email"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" onChange={handleChange} name='password' id="password" placeholder="Enter password"></input>
</div>
<button onClick={resetForm} type="submit" className="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Signup
This is Login.js
import React, { useState } from 'react';
import { useHistory } from 'react-router-dom';
import './Login.css';
const Login = () => {
let history = useHistory();
if (login.email && login.password === signupCredentials.email && signupCredentials.password) {
var redirect = () => {
history.push('/dashboard')
}
}
const [login, setLogin] = useState({})
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, login, { [name]: value })
setLogin(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(login)
}
const signupCredentials = JSON.parse(localStorage.getItem('userInfo'))
console.log(signupCredentials.email && signupCredentials.password)
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<form onSubmit={handleSubmit}>
<div className="form-group mb-2">
<label htmlFor="exampleInputEmail1">Email address</label>
<input type="email" className="form-control" onChange={handleChange} name='email' id="exampleInputEmail1" placeholder="Enter email"></input>
</div>
<div className="form-group mb-2">
<label htmlFor="exampleInputPassword1">Password</label>
<input type="password" className="form-control" onChange={handleChange} name='password' id="exampleInputPassword1" placeholder="Password"></input>
</div>
<button type="submit" onClick={redirect} className="btn btn-primary mt-3">Submit</button>
</form>
</div>
</div>
</div>
)
}
export default Login
If you have any questions please let me know

How to store object In Cookie in React using Hooks

I am working on a React project In my project I have a scenario to store object in Cookie.
This is my code Login.js
import React, { useState } from 'react';
import './Login.css';
const Login = () => {
const [data, setData] = useState('')
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
setData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
console.log(data)
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='main'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input type="email" className="form-control" name='email' id="email" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control" name='username' id="username" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" name='password' id="password" onChange={handleChange}></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Login
When I click submit button data will print in console. I have to store that in cookie
So what is the best way to store data object in Cookie
You can save the cookie in document.cookie. But you need to save the data as a string.
You could parse the whole object with JSON.parse, or the more elegant way is to use the specific attributes.
Cookies
But be aware that it is not save to store passwords in cookies.
Try this:
import React, { useState } from 'react';
import './Login.css';
const Login = () => {
const [data, setData] = useState('')
const handleChange = ({ target }) => {
const { name, value } = target
const newData = Object.assign({}, data, { [name]: value })
setData(newData)
}
const handleSubmit = (e) => {
e.preventDefault()
document.cookie = `email=${data.email}`;
document.cookie = `username=${data.username}`;
document.cookie = `password=${data.password}`;
}
return (
<div className='container'>
<div className='row justify-content-center'>
<div className='col-4'>
<div className='main'>
<form onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email address</label>
<input type="email" className="form-control" name='email' id="email" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="username">Username</label>
<input type="text" className="form-control" name='username' id="username" onChange={handleChange}></input>
</div>
<div className="form-group">
<label htmlFor="password">Password</label>
<input type="password" className="form-control" name='password' id="password" onChange={handleChange}></input>
</div>
<button type="submit" className="btn btn-primary">Submit</button>
</form>
</div>
</div>
</div>
</div>
)
}
export default Login
You just set data to cookie:
document.cookie =
of you can use some npm lib like this:
https://www.npmjs.com/package/react-cookie

Resources