Open a new component when the register button is clicked - reactjs

Open as a new page and the user goes inside the page when the button is clicked. How can I do it in react functional component? I want to navigate from Register to another MyProfile component when button is clicked. The code for Register component is as below:
import React, { useState } from 'react'
import './Register.css'
import axios from 'axios'
import { useHistory } from 'react-router-dom'
function Register() {
const history = useHistory();
const [data, setData] = useState({
name: "",
email: "",
password: "",
confirmpassword: "",
});
const register = (e) => {
e.preventDefault();
history.push("/myprofile")
}
const InputEvent = (event) => {
const { name, value } = event.target;
setData((preVal) => {
return {
...preVal,
[name]: value,
};
});
};
const formSubmit = (e) => {
e.preventDefault();
};
return (
<div className="signup__container">
<div className="signup__containerInfo">
<h1 className="h1__swari">swari</h1>
<hr />
</div>
<form4 onSubmit={formSubmit}>
<h5 className="h5__form"> Name</h5>
<input type="text" placeholder="Full Name" name="name" value={data.name} onChange={InputEvent} />
<h5 className="h5__form"> Email-Address </h5>
<input type="Email" placeholder="Email" name="email" value={data.email} onChange={InputEvent} />
<h5 className="h5__form"> Password </h5>
<input type="Password" placeholder="Password" name="password" value={data.password} onChange={InputEvent} />
<h5 className="h5__form"> Confirm Password </h5>
<input type="Password" placeholder="Confirm Password" name="confirmpassword" value={data.confirmpassword} onChange={InputEvent} />
<p>
<button onClick={register} type="submit" className="signup__registerButton" >Register Now</button>
</p>
</form4>
</div>
)
}
export default Register

Make a separate component of History.js
import { createBrowserHistory } from 'history';
export default createBrowserHistory();
Then in Register component.
import history from "../Shared/history";
const formSubmit = e => {
e.preventDefault();
history.push("/SomeComponent", {
someData: true,
otherData:{},
});
};
In Routes:
<Route path="/SomeComponent" component={Component} />

Related

submit form with react redux

i implement a single form for each sign up/ login with redux i test the apis with postman before trying to submit data with forms so the login form works fine but when i try to submit the register form nothing happened , just i got the console log message in the navigator console ..
here is my code :
form.js
import React, { useEffect } from "react";
import { Link, useNavigate } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";
import PropTypes from "prop-types";
import { useForm } from "react-hook-form";
import { login } from "../../redux/index";
import loginSvg from "../../images/Login-amico.svg";
import signUpSvg from "../../images/signup.svg";
function Form({ page }) {
const dispatch = useDispatch();
const navigate = useNavigate();
const userLogin = useSelector((state) => state.userLogin);
const { error: loginError, loading: loginLoading, userInfo } = userLogin;
const { register, handleSubmit } = useForm();
const onSubmit = (data) => {
if (page !== "signUp") {
dispatch(login(data.email, data.password));
} else {
console.log("smthg else");
}
};
useEffect(() => {
if (userInfo) {
navigate("/app/dashboard", { replace: true });
}
}, [navigate, userInfo]);
return (
<form onSubmit={handleSubmit(onSubmit)} >
{page === "signUp" ? (
<div className="mb-3">
<label>User Name</label>
<input
type="text"
className="form-control"
placeholder="user name"
{...register("userName", {
required: true,
className:
"form-control form-control-lg",
type: "text",
placeholder: "User Name",
})}
/>
</div>
) : undefined}
<div className="mb-3">
<label>Email address</label>
<input
type="email"
className="form-control"
placeholder="Enter email"
{...register("email", {
required: true,
className: "form-control",
type: "email",
placeholder: "Email address",
})}
/>
</div>
<div className="mb-3">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Enter password"
{...register("password", {
required: true,
className: "form-control",
type: "password",
placeholder: "Password",
})}
/>
</div>
<div className="d-grid">
<button type="submit" className="btn btn-primary">
Submit
</button>
</div>
<p className="forgot-password text-right">
Already registered sign in?
</p>
</form>
);
}
Form.propTypes = {
page: PropTypes.string.isRequired,
};
export default Form;
how can i solve this issue ?
Unfortunately I can't comment yet but I have a suggestion. I'm not very familiar with the useForm hook but I see in your onSubmit function that if page is signUp you will execute only a console.log message. Maybe you should add some dispatch to this condition as well.

Why my page is not redirecting to login page after successful registration in React?

Here, props.history.push("/login"); is not working
Other all things are Working
Can anyone Help?
import React, { useState } from 'react'
import { Link } from "react-router-dom";
import axios from "axios";
const Register = (props) => {
const [data, setData] = useState({
name: "",
email: "",
password: ""
})
const { name, email, password } = data;
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post(
"/auth/register", { name, email, password }, {
headers: {
"Content-Type": "application/json",
},
}
);
props.history.push("/login");
} catch (err) {
console.log(err);
}
};
return (
<form>
<h3>Create an account</h3>
<div className="mb-3">
<label>Name</label>
<input
type="text"
className="form-control"
placeholder="First name"
name="name"
value={name}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Email</label>
<input
type="email"
className="form-control"
placeholder="Enter email"
name="email"
value={email}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Enter Password"
name="password"
value={password}
onChange={handleChange}
/>
</div>
<div className="d-grid">
<button type="submit" className="btn btn-primary" onClick={handleSubmit}>
Register
</button>
</div>
<p className="forgot-password text-right">
Already registered? <Link to="/login">Login</Link>
</p>
</form>
);
}
export default Register
You have to try using this
import { useHistory } from "react-router-dom";
In function components
let history = useHistory();
After successfully register
history.push("/login");
Now it works
import React, { useState } from 'react'
import { Link } from "react-router-dom";
import axios from "axios";
import { useNavigate } from 'react-router-dom';
const Register = (props) => {
const [data, setData] = useState({
name: "",
email: "",
password: ""
})
const { name, email, password } = data;
const handleChange = (e) => {
setData({ ...data, [e.target.name]: e.target.value });
};
let navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
await axios.post(
"/auth/register", { name, email, password }, {
headers: {
"Content-Type": "application/json",
},
}
);
navigate("/login");
} catch (err) {
console.log(err);
}
};
return (
<form>
<h3>Create an account</h3>
<div className="mb-3">
<label>Name</label>
<input
type="text"
className="form-control"
placeholder="First name"
name="name"
value={name}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Email</label>
<input
type="email"
className="form-control"
placeholder="Enter email"
name="email"
value={email}
onChange={handleChange}
/>
</div>
<div className="mb-3">
<label>Password</label>
<input
type="password"
className="form-control"
placeholder="Enter Password"
name="password"
value={password}
onChange={handleChange}
/>
</div>
<div className="d-grid">
<button type="submit" className="btn btn-primary" onClick={handleSubmit}>
Register
</button>
</div>
<p className="forgot-password text-right">
Already registered? <Link to="/login">Login</Link>
</p>
</form>
);
}
export default Register

React onSubmit placement

I have looked at multiple sources for using onSubmit functions in React and they always place onSubmit triggers as a Form attribute, like this
import React, { Component } from "react";
import { connect } from "react-redux";
import PropTypes from "prop-types";
import { register } from "../../../actions/auth/auth.action";
import { Container } from "react-bootstrap";
import {
Button,
Form,
Label,
Input,
} from "reactstrap";
class Register extends Component {
state = {
fname: "",
lname: "",
email: "",
password: ""
};
static propTypes = {
register: PropTypes.func.isRequired
};
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
});
};
handleSubmit = e => {
e.preventDefault();
const { fname, lname, email, password } = this.state;
const newUser = {
name: {
first: fname,
last: lname
},
email: {
address: email
},
password
};
// Attempt to register user
this.props.register(newUser);
};
render() {
return(
<Form onSubmit={this.handleSubmit}>
<Label for="fname">First Name</Label>
<Input
type="text"
name="fname"
id="fname"
placeholder="Enter first name"
className="mb-3"
onChange={this.handleChange}
/>
<Label for="lname">Last Name</Label>
<Input
type="text"
name="lname"
id="lname"
placeholder="Enter last name"
className="mb-3"
onChange={this.handleChange}
/>
<Label for="email">Email</Label>
<Input
type="email"
name="email"
id="email"
placeholder="Enter email"
className="mb-3"
onChange={this.handleChange}
/>
<Label for="password">Password</Label>
<Input
type="password"
name="password"
id="password"
placeholder="Enter password"
className= "mb-3"
onChange={this.handleChange}
/>
<Button color="primary" style={{ marginTop: "2rem" }} block>
Register
</Button>
</Form>
);
};
};
const mapStateToProps = state => ({
error: state.error
});
export default connect(
mapStateToProps,
{ register }
)
(Register);
However, when I try this there is no way to call the function. (Ie. how does the button "know" when to call the onSubmit function when the call is a Form attrbute) I even tried added a type="submit" attribute to the button but that doesn't work either.
Just declare type="submit" in your button <button type="submit">send stuff</button> The type attribute is what onSubmit form is waiting for :) and remove e.preventDefault from your handleSubmit method and try again
The function will be called when submit event occurred.
Below code shows actions that trigger submit event.
class FormComponent extends React.Component {
handleSubmit = e => {
e.preventDefault();
console.log('submitted');
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<input type="submit" /><br />
<button>Button with no attribute</button><br />
<button type="submit">submit typed Button</button><br />
<button type="button">button typed Button (no submit)</button><br />
<input type="text" value="Press enter to submit" />
</form>
);
}
}
ReactDOM.render(
<FormComponent />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>

I have a form component I am passing to App.js but I am getting this error

Getting this error when render the app.
SignIn(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
SignIn.js
import React, { useState, useRef } from "react";
import axios from "axios";
import swal from "sweetalert";
import "./SignUp.css";
import image from './img/signup.jpg'
const SignIn = () => {
const [creds, setCreds] = useState({ userName: "", password: "" });
const usernameFieldRef = useRef();
const passwordFieldRef = useRef();
const changeHandler = e => {
setCreds({ ...creds, [e.target.name]: e.target.value });
};
const handleSubmit = event => {
event.preventDefault();
console.log('login');
const username = usernameFieldRef.current.value;
const password = passwordFieldRef.current.value;
axios
.post("https://foodiefun-api.herokuapp.com/api/auth/login", {
username,
password
})
.then(res => {
console.log("DATA", res.data)
localStorage.setItem('token', res.data.token)
swal(
"Welcome to Foodie Fun!",
"You are now signed in, enjoy your stay!",
"success"
);
})
.catch(err => {
console.log('LOGIN FAILED', err.response); // There was an error creating the data and logs to console
});
return (
<div class="page-content">
<div class="form-v6-content">
<div class="form-left">
<img className="form-image" style={{ linearGradient: "red, blue", opacity: ".6" }} src={image} alt="form" />
</div>
<form
onSubmit={handleSubmit}
class="form-detail"
method="post">
<h2>Register Form</h2>
<div class="form-row">
<input
ref={usernameFieldRef}
onChange={changeHandler}
// value={creds.userName}
type="text"
name="id"
id="user-name"
class="input-text"
placeholder="Enter Desired User Name"
required />
</div>
<div class="form-row">
<input
ref={passwordFieldRef}
onChange={changeHandler}
value={creds.password}
type="password"
name="password"
id="password"
class="input-text"
placeholder="Password"
required />
</div>
<div class="form-row">
<input
type="password"
name="comfirm-password"
id="comfirm-password"
class="input-text"
placeholder="Comfirm Password"
required />
</div>
<div class="form-row-last">
<input type="submit"
name="register"
class="register"
value="Register" />
</div>
</form>
</div>
</div>
)
}
}
export default SignIn
App.js
import React, { useState } from "react";
import "./App.css";
import Form from "./Components/SignIn";
import ReviewForm from "./Components/ReviewForm/ReviewForm";
import UserInfo from "./Components/userInfo";
import mockarray from "./Components/mockarray";
import Navbar from "./Components/Navbar";
import RecipeApp from "./recipes/RecipeApp";
import SignUp from "./Components/SignUp";
import SignIn from "./Components/SignIn";
const App = () => {
const [reviews, setReviews] = useState([]);
const addReview = restaurant => {
setReviews([...reviews, { ...restaurant, id: Date.now() }]);
};
return (
<div className="App">
<Navbar />
<SignUp />
<SignIn />
{/* <RecipeApp /> */}
{/* <ReviewForm /> */}
{/* <ReviewForm addReview={addReview} /> */}
{console.log(reviews)}
{/* <UserInfo data = {mockarray} /> */}
</div>
);
};
export default App;
Two forms should be rendering on the screen but when I comment in the SignIn page I get this error. A couple of people have looked at it and they both say everything is right. I'm stumped!
Your return statement is inside the handleSubmit function.
You need to return your state outside handleSubmit function :
import React, { useState, useRef } from "react";
import axios from "axios";
import swal from "sweetalert";
import "./SignUp.css";
import image from './img/signup.jpg'
const SignIn = () => {
const [creds, setCreds] = useState({ userName: "", password: "" });
const usernameFieldRef = useRef();
const passwordFieldRef = useRef();
const changeHandler = e => {
setCreds({ ...creds, [e.target.name]: e.target.value });
};
const handleSubmit = event => {
event.preventDefault();
console.log('login');
const username = usernameFieldRef.current.value;
const password = passwordFieldRef.current.value;
axios
.post("https://foodiefun-api.herokuapp.com/api/auth/login", {
username,
password
})
.then(res => {
console.log("DATA", res.data)
localStorage.setItem('token', res.data.token)
swal(
"Welcome to Foodie Fun!",
"You are now signed in, enjoy your stay!",
"success"
);
})
.catch(err => {
console.log('LOGIN FAILED', err.response); // There was an error creating the data and logs to console
});
}
return (
<div class="page-content">
<div class="form-v6-content">
<div class="form-left">
<img className="form-image" style={{ linearGradient: "red, blue", opacity: ".6" }} src={image} alt="form" />
</div>
<form
onSubmit={handleSubmit}
class="form-detail"
method="post">
<h2>Register Form</h2>
<div class="form-row">
<input
ref={usernameFieldRef}
onChange={changeHandler}
// value={creds.userName}
type="text"
name="id"
id="user-name"
class="input-text"
placeholder="Enter Desired User Name"
required />
</div>
<div class="form-row">
<input
ref={passwordFieldRef}
onChange={changeHandler}
value={creds.password}
type="password"
name="password"
id="password"
class="input-text"
placeholder="Password"
required />
</div>
<div class="form-row">
<input
type="password"
name="comfirm-password"
id="comfirm-password"
class="input-text"
placeholder="Comfirm Password"
required />
</div>
<div class="form-row-last">
<input type="submit"
name="register"
class="register"
value="Register" />
</div>
</form>
</div>
</div>
)
}
export default SignIn
Working code : https://codesandbox.io/s/divine-field-kkfd6
Not sure if it's a typo on the code of your question or in your acctual code but the return is inside handleSubmit.
import React, { useState, useRef } from 'react'
import axios from 'axios'
import swal from 'sweetalert'
import './SignUp.css'
import image from './img/signup.jpg'
const SignIn = () => {
const [creds, setCreds] = useState({ userName: '', password: '' })
const usernameFieldRef = useRef()
const passwordFieldRef = useRef()
const changeHandler = e => {
setCreds({ ...creds, [e.target.name]: e.target.value })
}
const handleSubmit = event => {
event.preventDefault()
console.log('login')
const username = usernameFieldRef.current.value
const password = passwordFieldRef.current.value
axios
.post('https://foodiefun-api.herokuapp.com/api/auth/login', {
username,
password
})
.then(res => {
console.log('DATA', res.data)
localStorage.setItem('token', res.data.token)
swal(
'Welcome to Foodie Fun!',
'You are now signed in, enjoy your stay!',
'success'
)
})
.catch(err => {
console.log('LOGIN FAILED', err.response) // There was an error creating the data and logs to console
})
}
return (
<div className="page-content">
<div className="form-v6-content">
<div className="form-left">
<img
className="form-image"
style={{ linearGradient: 'red, blue', opacity: '.6' }}
src={image}
alt="form"
/>
</div>
<form onSubmit={handleSubmit} className="form-detail" method="post">
<h2>Register Form</h2>
<div className="form-row">
<input
ref={usernameFieldRef}
onChange={changeHandler}
// value={creds.userName}
type="text"
name="id"
id="user-name"
className="input-text"
placeholder="Enter Desired User Name"
required
/>
</div>
<div className="form-row">
<input
ref={passwordFieldRef}
onChange={changeHandler}
value={creds.password}
type="password"
name="password"
id="password"
className="input-text"
placeholder="Password"
required
/>
</div>
<div className="form-row">
<input
type="password"
name="comfirm-password"
id="comfirm-password"
className="input-text"
placeholder="Comfirm Password"
required
/>
</div>
<div className="form-row-last">
<input
type="submit"
name="register"
className="register"
value="Register"
/>
</div>
</form>
</div>
</div>
)
}
export default SignIn

the state inside hooks are not updated for first time on form submit in react

I was trying to implement contactUS form in react using hooks.Contact us form is placed inside hooks.When I first submit the form the state in hooks are not updated ,when I click 2nd time states are set .and I am returning state to class component there api call are made.
//contactushook.js
import React, { useState } from 'react';
const ContactUshook = ({ parentCallBack }) => {
const [data, setData] = useState([]);
const handleSubmit = (event) => {
event.preventDefault();
setData({ name: document.getElementById('name').value, email: document.getElementById('email').value, message: document.getElementById('message').value });
console.log(data);
parentCallBack(data);
}
return <React.Fragment>
<div className="form-holder">
<form onSubmit={handleSubmit}>
<div>
<input id="name" type="text" placeholder="enter the name"></input>
</div>
<div>
<input id="email" type="email" placeholder="enter the email"></input>
</div>
<div>
<textarea id="message" placeholder="Type message here"></textarea>
</div>
<button type="submit" >Submit</button>
</form>
</div>
</React.Fragment >
}
export default ContactUshook;
//contactus.js
import React, { Component } from 'react';
import ContactUshook from './hooks/contactushook';
import '../contactUs/contactus.css';
class ContactComponent extends Component {
onSubmit = (data) => {
console.log('in onsubmit');
console.log(data);
}
render() {
return (
<div>
<h4>hook</h4>
<ContactUshook parentCallBack={this.onSubmit}></ContactUshook>
</div>
);
}
}
export default ContactComponent;
Stop using document queries and start using state instead!
Your ContactUshook component should look like this:
const ContactUshook = ({ parentCallBack }) => {
const [data, setData] = useState({ name: '', email: '', message: '' });
const handleSubmit = () => {
event.preventDefault();
parentCallBack(data);
}
const handleChange = (event, field) => {
const newData = { ...data };
newData[field] = event.target.value;
setData(newData);
}
return (
<div className="form-holder">
<form onSubmit={handleSubmit}>
<div>
<input
id="name"
type="text"
value={data.name}
placeholder="enter the name"
onChange={(e) => handleChange(e,'name')} />
</div>
<div>
<input
id="email"
type="email"
value={data.email}
placeholder="enter the email"
onChange={(e) => handleChange(e,'email')} />
</div>
<div>
<textarea
id="message"
value={data.message}
placeholder="Type message here"
onChange={(e) => handleChange(e,'message')} />
</div>
<button type="submit" >Submit</button>
</form>
</div>
);
}

Resources