How can I pass data using <Redirect> in react router v4? - reactjs

The situation is that I use axios gain data from back-end and I want to redirect from current page to another page as well as passing some data.
How can I pass data when I use <Redirect> to redirect?
I am using code like below, and I can't get 'profile' at the destination page. No matter, this.props or this.state
I understand that using react-router-redux is a better choice.
import React, { Component } from 'react'
import axios from 'axios'
import { Redirect } from 'react-router'
export default class Login extends Component {
constructor(props) {
super(props)
this.state = {
email: '',
emailError: 'Please fill in email',
password: '',
passwordError: 'Please fill in password',
redirect: false,
profile: ''
}
this.handleEmail = (e) => {
var email = e.target.value
var emailError = ''
if (email === null)
emailError = 'Please fill in email'
this.setState({
email: email,
emailError: emailError
})
}
this.handlePassword = (e) => {
var password = e.target.value
var passwordError = ''
if (password === null)
passwordError = 'Please fill in password'
this.setState({
password: password,
passwordError: passwordError
})
}
this.handleSubmit = (e) => {
e.preventDefault()
if (this.state.emailError)
alert(this.state.emailError)
else if (this.state.passwordError)
alert(this.state.passwordError)
else {
axios.post('/user/login', {
email: this.state.email,
password: this.state.password
}).then(response => {
if (response.data !== 'fail') {
this.setState({
redirect: true,
profile: response.data
})
}
})
}
}
}
render() {
const { redirect, profile } = this.state
if (redirect)
return (<Redirect to={{
pathname: '/user/profile',
state: { referrer: this.state.profile }
}} />)
return (
<div className="content user">
<div className="container">
<div className="row">
<div className="col-xs-12">
<h1>Log In Your Tutor Profile</h1>
<form role="form" noValidate>
<div className="row">
<div className="col-xs-12">
<label htmlFor="email">Email</label>
<div className="form-group">
<input id="email" type="text" className="form-control" value={this.state.email} onChange={this.handleEmail} name="email" required/>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-12">
<label htmlFor="password">Password</label>
<div className="form-group">
<input id="password" type="password" className="form-control" value={this.state.password} onChange={this.handlePassword} name="password" required/>
</div>
</div>
</div>
<div className="row">
<div className="col-xs-12">
<div className="form-group">
<button className="btn btn-primary submit" onClick={this.handleSubmit}>LOG IN YOUR PROFILE</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
)
}
}

The way you are passing your state to the Redirect is correct, the only place the problem should be is how you are accessing it. State can be accessed like this.props.location.state. However if you directly route to the path then state won't we available so you need to add a check
Access your state like
this.props.location.state && this.props.location.state.referrer

Related

Using history.push() while using a component within another component

Suppose I have a component named "Welcome.js" which is a welcome page for a ecommerce website. It renders some information about the page and then has a sign-up option beside it. The sign-up part, I have written as another component and called it from Welcome.js. When the correct credentials are passed, signup page is supposed to redirect to a dashboard. This is working fine with the individual component page of "Sign-up.js". But when the same thing is done from welcome page,I'm getting the following error :TypeError: Cannot read property 'push' of undefined
I am new to React so my terminology might be wrong. Im assuming the error occured because im calling history.push() from a component which is within another component. Is there any workaround for this?
Welcome.js
import {Link} from 'react-router-dom';
class Welcome extends Component {
constructor(props) {
super();
this.handleSubmit = this.handleSubmit.bind(this)
}
handleSubmit() {
this.props.history.push('/SignUp')
}
render() {
return (
<div className="Welcome">
<body>
<nav>
<input type="checkbox" id="check"/>
<label htmlFor="check" className="checkBtn">
<i className="fas fa-bars"/>
</label>
<label className="logo">EStock</label>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/About">About</Link></li>
<li><Link to="/Contact">Contact</Link></li>
<li><Link to="/SignIn">Sign in</Link></li>
<li className="createAccountShort"><Link to="/SignUp">Create Account</Link></li>
</ul>
</nav>
<div className="content">
<h1>A New Way to Invest</h1>
<p>EStock is the best platform to help you analyse the latest stock trends
and decide the stock through which you can grow your wealth.</p>
<button onClick={this.handleSubmit} className="createAccount">Create Account ></button>
</div>
</body>
</div>
);
}
}
export default Welcome
SignIn.js
import {Link} from "react-router-dom";
class SignIn extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
errorMessage: false
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.validateForm = this.validateForm.bind(this);
}
async handleSubmit(event) {
event.preventDefault();
event.stopPropagation();
let response = await fetch('/customer/validateLogin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*'
},
body: JSON.stringify({
emailId: this.state.email,
password: this.state.password
})
});
let status = response.status;
if (status === 200) {
this.props.history.push({
pathname: '/DashBoard',
customer: await response.json()
});
} else if (status === 404) {
this.setState({
errorMessage: true
})
} else {
this.props.history.push({
pathname: '/Error404',
message: 'Backend server is down'
});
}
}
handleChange = (event) => {
const {name, value} = event.target
this.setState({
[name]: value
})
}
validateForm() {
return this.state.email.length > 0 && this.state.password.length > 0;
}
render() {
return (
<div>
<div className="NAV">
<nav>
<input type="checkbox" id="check"/>
<label htmlFor="check" className="checkBtn">
<i className="fas fa-bars"/>
</label>
<label className="logo">EStock</label>
<ul>
<li><Link to="/">Welcome</Link></li>
<li><Link to="/About">About</Link></li>
<li><Link to="/Contact">Contact</Link></li>
</ul>
</nav>
</div>
<div className="SignUp">
<div className="register">
<h1>Enter your Credentials</h1>
<p>New at the portal?<Link to="/SignUp"> Sign Up</Link></p>
</div>
<div className="main">
<form onSubmit={this.handleSubmit}>
<h2 className="name">Email Address</h2>
<input
type="email"
name="email"
required="True"
className="email"
placeholder="Email address"
value={this.state.email}
onChange={this.handleChange}
/>
<br/>
<h2 className="name">Password</h2>
<input
type="password"
name="password"
required="True"
className="password"
placeholder="Password"
value={this.state.password}
onChange={this.handleChange}
/>
<h3 style={{display: this.state.errorMessage ? "block" : "none", color: "white"}}>Incorrect
Username/Password</h3>
<button className="registerButton" disabled={!this.validateForm}>Sign in</button>
</form>
</div>
</div>
</div>
);
}
}
export default SignIn```
import React, {Component} from "react";
import {Link} from "react-router-dom";
class SignIn extends Component {
constructor(props) {
super(props);
this.state = {
email: "",
password: "",
errorMessage: false
}
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
this.validateForm = this.validateForm.bind(this);
}
async handleSubmit(event) {
event.preventDefault();
event.stopPropagation();
let response = await fetch('/customer/validateLogin', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*'
},
body: JSON.stringify({
emailId: this.state.email,
password: this.state.password
})
});
let status = response.status;
if (status === 200) {
this.props.history.push({
pathname: '/DashBoard',
customer: await response.json()
});
} else if (status === 404) {
this.setState({
errorMessage: true
})
} else {
this.props.history.push({
pathname: '/Error404',
message: 'Backend server is down'
});
}
}
handleChange = (event) => {
const {name, value} = event.target
this.setState({
[name]: value
})
}
validateForm() {
return this.state.email.length > 0 && this.state.password.length > 0;
}
render() {
return (
<div>
<div className="NAV">
<nav>
<input type="checkbox" id="check"/>
<label htmlFor="check" className="checkBtn">
<i className="fas fa-bars"/>
</label>
<label className="logo">EStock</label>
<ul>
<li><Link to="/">Welcome</Link></li>
<li><Link to="/About">About</Link></li>
<li><Link to="/Contact">Contact</Link></li>
</ul>
</nav>
</div>
<div className="SignUp">
<div className="register">
<h1>Enter your Credentials</h1>
<p>New at the portal?<Link to="/SignUp"> Sign Up</Link></p>
</div>
<div className="main">
<form onSubmit={this.handleSubmit}>
<h2 className="name">Email Address</h2>
<input
type="email"
name="email"
required="True"
className="email"
placeholder="Email address"
value={this.state.email}
onChange={this.handleChange}
/>
<br/>
<h2 className="name">Password</h2>
<input
type="password"
name="password"
required="True"
className="password"
placeholder="Password"
value={this.state.password}
onChange={this.handleChange}
/>
<h3 style={{display: this.state.errorMessage ? "block" : "none", color: "white"}}>Incorrect
Username/Password</h3>
<button className="registerButton" disabled={!this.validateForm}>Sign in</button>
</form>
</div>
</div>
</div>
);
}
}
export default SignIn
Your child component does not have the routing props. You need to inject routing props to the child component. You can do that by wrapping the child in a HOC and use withRouter.
You need to wrap your Welcome component in withRouter HOC
import { withRouter } from "react-router";
....
export default withRouter(Welcome)
https://reactrouter.com/web/api/withRouter

Redirection to dashboard after login in react

I have a login page, and I want to redirect users to dashboard after the details are filled.
I have tried using history.push and redirect components but I couldn't redirect.
Login Page
class Login extends React.Component {
state = {
email: '',
password: '',
errors: {},
redirect: false
}
validateForm = () => {
let errors = {};
let formIsValid = true;
if(!this.state.email) {
formIsValid = false;
errors['email'] = 'Please enter email to continue';
}
if(!this.state.password) {
formIsValid = false;
errors['password'] = 'Please enter password to continue';
}
this.setState({
errors: errors
})
return formIsValid;
}
handleChange = (event) => {
this.setState({
[event.target.id]: event.target.value
});
}
handleSubmit = (event) => {
event.preventDefault();
// console.log(this.state);
if(this.validateForm()) {
const loginData = {
email: this.state.email,
password: this.state.password
}
axios
.post('/users.json', loginData)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
})
}
}
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">Login</h5>
<div className="input-field">
<label htmlFor="email">Email</label>
<input type="email" id="email" onChange={this.handleChange} />
<p>{this.state.errors.email}</p>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input type="password" id="password" onChange={this.handleChange} />
<p>{this.state.errors.password}</p>
</div>
<div className="input-field">
<button onClick={this.redirectHandler} className="btn btn-primary">Login</button>
</div>
</form>
</div>
)
}
}
export default Login;
I want to redirect to other page once the form is submitted with the email and password.
I've been trying this for days but I couldn't find a solution.
import { withRouter } from 'react-router';
class Login extends React.Component {
state = {
email: '',
password: '',
errors: {},
redirect: false
}
validateForm = () => {
let errors = {};
let formIsValid = true;
if(!this.state.email) {
formIsValid = false;
errors['email'] = 'Please enter email to continue';
}
if(!this.state.password) {
formIsValid = false;
errors['password'] = 'Please enter password to continue';
}
this.setState({
errors: errors
})
return formIsValid;
}
handleChange = (event) => {
this.setState({
[event.target.id]: event.target.value
});
}
handleSubmit = (event) => {
event.preventDefault();
// console.log(this.state);
if(this.validateForm()) {
const loginData = {
email: this.state.email,
password: this.state.password
}
axios
.post('/users.json', loginData)
.then(response => {
this.props.history.push("/dashboard");
console.log(response.data);
})
.catch(error => {
console.log(error);
})
}
}
render() {
return (
<div className="container">
<form onSubmit={this.handleSubmit} className="white">
<h5 className="grey-text text-darken-3">Login</h5>
<div className="input-field">
<label htmlFor="email">Email</label>
<input type="email" id="email" onChange={this.handleChange} />
<p>{this.state.errors.email}</p>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input type="password" id="password" onChange={this.handleChange} />
<p>{this.state.errors.password}</p>
</div>
<div className="input-field">
<button onClick={this.redirectHandler} className="btn btn-primary">Login</button>
</div>
</form>
</div>
)
}
}
export default withRouter(Login);
have some complain about your code.
first: for form validation and handling you dont need to use state,
there is a library called Formik which will help you a lot with
this.
second: if you are using redux to check user is logged in or
not you need to create a private route for routes which cannot be
accessible for public like here dashboard component.
third: to use history you need to wrap your
component inside withRouter HOC which will pass route props to your
component so you can use history or if your are using functional component you can use useHistory() hook.

ComboBox doesn't show after setState or forceUpdate

my problem is that I want to get info If I'm authorized from API using axios.get before rendering the page. I did something like that. Everything is working perfectly but my with a role to choose doesn't show.
I'm new in react. "this.forceUpdate()" <- same problem
If I delete my authorization check, eliminate const{authorized} = this.state and {authorized ?(...) I see the combobox.
class RegisterComponent extends Component {
componentDidMount() {
this.checkAuthorizationStatus();
M.AutoInit();
}
checkAuthorizationStatus(){
axios.get(API_URL+`/logged_in`)
.then(response=>{
if(response.data.authenticated === true && response.data.principal.authorities[0].authority===`ROLE_ADMIN`){
this.setState({authorized:true})
}
else{
return <Redirect to="/login" />
}
})
}
constructor(props) {
super(props)
this.state = {
username: '',
password: '',
role : 'ROLE_ADMIN',
hasCreationFailed: false,
showSuccessMessage: false,
authorized : false,
}
}
handleChange = (event) => {
this.setState(
{
[event.target.name]: event.target.value
}
)
}
submitClicked = () => {
console.log({login: this.state.username,
password: this.state.password,
roles: [{"role":this.state.role}]})
axios.post(API_URL + '/admin/register', {
login: this.state.username,
password: this.state.password,
roles: [{"role":this.state.role}]
})
.then((response) => {
this.setState({
showSuccessMessage: true,
hasCreationFailed: false
}
)
console.log(response)
})
.catch((error) => {
this.setState({
showSuccessMessage: false,
hasCreationFailed: true
})
console.log(error)
})
}
render() {
const{authorized} = this.state
return (
<React.Fragment>
{authorized ?(
<div className="row container">
<div className="col s10 offset-s1 l4 offset-l4">
<div className="purple-text accent-2"><h5>Create New Account</h5></div>
<div className="input-field">
<select value={this.state.role} onChange={this.handleChange} name="role">
<option value='ROLE_ADMIN'>Administrator</option>
<option value='ROLE_TABLE'>Klient</option>
<option value='ROLE_WORKER'>Pracownik</option>
</select>
</div>
<div className="input-field">
<input className="validate" type="text" id="username" name="username"
value={this.state.username} onChange={this.handleChange}/>
<label htmlFor="username">Username</label>
</div>
<div className="input-field">
<label htmlFor="password">Password</label>
<input type="password" id="password" name="password" value={this.state.password}
onChange={this.handleChange}/>
</div>
<button className="btn blue col l12 waves-effect waves-light"
onClick={this.submitClicked}>Zarejestruj użytkownika
</button>
{this.state.showSuccessMessage &&
<div className="green-text">Rejestracja zakończona powodzeniem</div>}
{this.state.hasCreationFailed && <div className="red-text">Rejestracja nie powiodła się</div>}
</div>
</div>
):(<></>)}
</React.Fragment>
)}
}
export default RegisterComponent
Could anyone help me?
Update the role property of state in your handleChange since your <select> uses value from this.state.role
handleChange = (event) => {
this.setState(
{
role: event.target.value // update 'role' property
}
)
}

how do i use <redirect/> for redirecting to a different page after login authentication?

I am doing a project on Reactjs and I'm new to it. Its just been few days since i have been working on Reactjs. I want to redirect to a new page after successfull login authentication. I am using but its not working, and being new to reactjs i cant figure out where i am going wrong. My redirect condition being if both "valid" and "proceed" = false then it will redirect it to another page. The boolean values for "valid" and "proceed" comes from a http response and its working fine but redirect it not working. The page remains as it is.
My sigin component : SignInForm.js->
import React, { Component } from "react";
import { Link, Redirect } from "react-router-dom";
import axios from "axios";
class SignInForm extends Component {
state = {
email: "",
pass: "",
proceed: false,
valid: false
};
passwordChange = event => {
this.setState({ pass: event.target.value });
};
emailChange = event => {
this.setState({ email: event.target.value });
};
handleOperation = event => {
event.preventDefault();
const user = this.state.email;
const pwd = this.state.pass;
console.log(user + "|" + pwd);
this.setState({
loading: true
});
const data = {
user,
pwd
};
axios
.post("https://some end-point where i make my request", data)
.then(res => {
console.log(res);
this.setState({
proceed: res.data.proceed,
valid: res.data.valid
});
console.log(
"res pro= " + res.data.proceed + "| res val=" + res.data.valid
);
console.log(
"state pro=" +
this.state.proceed +
"|" +
"state val = " +
this.state.valid
);
if (!this.state.proceed && !this.state.valid) {
console.log(" In condition");
return <Redirect to="/Demo" />;
}
})
.catch(err => {
console.log(err);
});
};
render() {
return (
<div className="FormCenter">
<form className="FormFields">
<div className="FormField">
<label className="FormField__Label" htmlFor="email">
E-Mail Address
</label>
<input
type="email"
id="email"
className="FormField__Input"
placeholder="Enter your e-mail address"
name="email"
onChange={this.emailChange}
/>
</div>
<div className="FormField">
<label className="FormField__Label" htmlFor="password">
Password
</label>
<input
type="password"
id="password"
className="FormField__Input"
placeholder="Enter your password"
name="password"
onChange={this.passwordChange}
/>
</div>
<div className="FormField">
<button
className="FormField__Button mr-20"
onClick={this.handleOperation}
>
Sign In
</button>
<Link to="/" className="FormField__Link">
Create a new account
</Link>
</div>
</form>
</div>
);
}
}
export default SignInForm;`
Demo Component :Demo.js ->
import React, { Component } from "react";
class Demo extends Component {
render() {
return <h1>THIS IS A DEMO</h1>;
}
}
export default Demo;
Use Redirect in render as it is a component. Also make initial state for valid & proceed as strings instead of boolean (otherwise it'll always be redirecting, as initial state will be always be false for both) and update the redirection condition also to incorporate that.
import React, { Component } from "react";
import { Link, Redirect } from "react-router-dom";
import axios from "axios";
class SignInForm extends Component {
state = {
email: "",
pass: "",
proceed: "false",
valid: "false"
};
passwordChange = event => {
this.setState({ pass: event.target.value });
};
emailChange = event => {
this.setState({ email: event.target.value });
};
handleOperation = event => {
event.preventDefault();
const user = this.state.email;
const pwd = this.state.pass;
console.log(user + "|" + pwd);
this.setState({
loading: true
});
const data = {
user,
pwd
};
axios
.post("https://some end-point where i make my request", data)
.then(res => {
this.setState({
proceed: res.data.proceed,
valid: res.data.valid
});
})
.catch(err => {
console.log(err);
});
};
render() {
if ( this.state.proceed===false && this.state.valid===false) {
return <Redirect to="/Demo" />;
}
return (
<div className="FormCenter">
<form className="FormFields">
<div className="FormField">
<label className="FormField__Label" htmlFor="email">
E-Mail Address
</label>
<input
type="email"
id="email"
className="FormField__Input"
placeholder="Enter your e-mail address"
name="email"
onChange={this.emailChange}
/>
</div>
<div className="FormField">
<label className="FormField__Label" htmlFor="password">
Password
</label>
<input
type="password"
id="password"
className="FormField__Input"
placeholder="Enter your password"
name="password"
onChange={this.passwordChange}
/>
</div>
<div className="FormField">
<button
className="FormField__Button mr-20"
onClick={this.handleOperation}
>
Sign In
</button>
<Link to="/" className="FormField__Link">
Create a new account
</Link>
</div>
</form>
</div>
);
}
}
export default SignInForm;`
Hope this helps ! Happy coding.
Redirect is a component that needs to be rendered. Also setState is async and so its value may not update immediately.
import React, { Component } from "react";
import { Link, Redirect } from "react-router-dom";
import axios from "axios";
class SignInForm extends Component {
state = {
email: "",
pass: "",
proceed: false,
valid: false
};
passwordChange = event => {
this.setState({ pass: event.target.value });
};
emailChange = event => {
this.setState({ email: event.target.value });
};
handleOperation = event => {
event.preventDefault();
const user = this.state.email;
const pwd = this.state.pass;
console.log(user + "|" + pwd);
this.setState({
loading: true
});
const data = {
user,
pwd
};
axios
.post("https://some end-point where i make my request", data)
.then(res => {
console.log(res);
this.setState({
proceed: res.data.proceed,
valid: res.data.valid
});
console.log(
"res pro= " + res.data.proceed + "| res val=" + res.data.valid
);
console.log(
"state pro=" +
this.state.proceed +
"|" +
"state val = " +
this.state.valid
);
})
.catch(err => {
console.log(err);
});
};
render() {
if (!this.state.proceed && !this.state.valid) {
console.log(" In condition");
return <Redirect to="/Demo" />;
}
return (
<div className="FormCenter">
<form className="FormFields">
<div className="FormField">
<label className="FormField__Label" htmlFor="email">
E-Mail Address
</label>
<input
type="email"
id="email"
className="FormField__Input"
placeholder="Enter your e-mail address"
name="email"
onChange={this.emailChange}
/>
</div>
<div className="FormField">
<label className="FormField__Label" htmlFor="password">
Password
</label>
<input
type="password"
id="password"
className="FormField__Input"
placeholder="Enter your password"
name="password"
onChange={this.passwordChange}
/>
</div>
<div className="FormField">
<button
className="FormField__Button mr-20"
onClick={this.handleOperation}
>
Sign In
</button>
<Link to="/" className="FormField__Link">
Create a new account
</Link>
</div>
</form>
</div>
);
}
}
export default SignInForm;

Storing data in multiple tables in react on the basis of role

I'm new to react and i'm building a website in which user is added on the basis of role. While adding user information, user selects a role in drop down. I have a table for Role in which only roles are kept(admin, teacher and team lead), a User table which contains user information( name, email password, etc) and a UserRole table which will have a userID and a roleID to represent which role is assigned to which user. I'm using asp.net core web-API to get and post data.
I just can't figure that out how to save roleID against the role that has been selected and userID of user in UserRole table.
can please someone help me with it?
Here is my react code of file Adduser.tsx
import * as React from 'react';
//import { ReactComponent } from '*.svg';
import '../css/form.css';
import Sidebar from '../Component/sidebar/sidebar';
const axios = require('axios');
class Adduser extends React.Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
teacherId: 0,
name: '',
email: '',
password: '',
confirmPassword: '',
gender: '',
question: [],
nameError: '',
passError: '',
emailError: ''
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handlePasswordChange = this.handlePasswordChange.bind(this);
}
componentWillMount() {
if (this.props.match.params.id != undefined) {
axios.get('https://localhost:44310/api/Users/' + this.props.match.params.id)
.then((response: any) => {
this.setState({
teacherId: response.data.teacherId,
name: response.data.name,
email: response.data.email,
password: response.data.password,
confirmPassword: response.data.confirmPassword,
gender: response.data.gender,
role: response.data.role,
question: []
});
})
.catch((error: any) => {
console.log(error);
});
}
}
handleChange = (event: any) => {
this.setState({ [event.target.name]: event.target.value }, () => this.validateName())
}
handlePasswordChange = (event: any) => {
this.setState({ [event.target.name]: event.target.value }, () => this.validatePassword())
}
validateName() {
const { name } = this.state;
this.setState(
{ nameError: name.length > 3 ? null : 'Name must contain atleast 3 characters' }
// passError: password.length > 3 || password ? null : 'Password must contain atleast 6 characters'}
)
}
validatePassword() {
const { password } = this.state;
this.setState({
passError: password.length > 6 ? null : 'Password must contain atleast 6 characters'
}
)
}
validateEmail(email: any) {
const pattern = /[a-zA-Z0-9]+[\.]?([a-zA-Z0-9]+)?[\#][a-z]{3,9}[\.][a-z]{2,5}/;
const result = pattern.test(email);
if (result === true) {
this.setState({
emailError: false,
email: email
})
} else {
this.setState({
emailError: true
})
}
// email = $('email');
// var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
// if (filter.test(email.value)) {
// // Yay! valid
// return '';
// }
// else
// return 'invalid email';
}
handleSubmit(event: any) {
event.preventDefault();
if (this.props.match.params.id != undefined) {
const { password, confirmPassword } = this.state
if (password !== confirmPassword) {
alert('passwords do not match')
}
else {
axios.put(`https://localhost:44310/api/Users/${this.props.match.params.id}`, this.state)
.then((response: any) => {
this.props.history.push('/');
})
.catch(function (error: any) {
console.log(error);
});
}
} else {
const { password, confirmPassword, name } = this.state
if (password !== confirmPassword) {
alert('passwords do not match')
}
else {
axios.post('https://localhost:44310/api/Users/', this.state)
.then((response: any) => {
console.log(response);
alert('User has been added successfully')
})
.catch(function (error: any) {
console.log(error);
alert('Sorry! Your request can not be processed at the moment')
});
}
}
}
render() {
return (
<div className="row">
<div className=" col-lg-2">
<Sidebar />
</div>
<div className="col-lg-10">
<div className="content" >
<div className="container-fluid">
<div className="row" >
<div className="col-lg-3"> </div>
<div className="col-lg-6" style={{ paddingTop: "30px" }}>
<div id="ui">
{this.props.match.params.id != undefined ? <h1 style={{ marginTop: "15px" }}>EDIT ACCOUNT</h1> : <h1 style={{ marginTop: "15px" }}>ADD ACCOUNT</h1>}
<form className="form-group" method="post" onSubmit={this.handleSubmit} autoComplete="off">
<label> Name:</label>
<div className="name">
<input type="text"
onChange={this.handleChange}
name="name"
value={this.state.name}
className={`form-control ${this.state.nameError ? 'is-invalid' : ''}`}
placeholder="Enter username " required
onBlur={this.validateName.bind(this)} />
<div className="invalid-feedback">Name must be longer than 3 characters</div>
</div>
<br />
<label> Email:</label>
<div className="mail">
<input type="email" name="email" value={this.state.email} onChange={this.handleChange} className="form-control" placeholder="Enter E-mail" required />
<div className="invalid-feedback">Email is invalid</div>
</div>
<br />
<div className="row">
<div className="col-lg-6">
<label> Password:</label>
<div className="pass">
<input type="password" name="password" value={this.state.password} onChange={this.handlePasswordChange} className={`form-control ${this.state.passError ? 'is-invalid' : ''}`} id="pwd" placeholder="Enter password" required onBlur={this.validatePassword.bind(this)} />
<div className="invalid-feedback">Password must be longer than 6 characters</div>
</div>
</div>
<div className="col-lg-6">
<label> Re-type Password:</label>
<div className="pass1">
<input type="password" name="confirmPassword" value={this.state.pass1} onChange={this.handleChange} className="form-control" id="pwd1" placeholder="Re-type password" required />
</div>
</div>
<br />
<div className="col-lg-12">
<select className="form-control" name="gender" value={this.state.gender} onChange={this.handleChange} id="sel" style={{ marginTop: "35px" }} required>
<option>Choose Gender</option>
<option>Male</option>
<option>Female</option>
</select>
</div>
<br />
<div className="col-lg-12">
<select className="form-control" name="role" value={this.state.role} onChange={this.handleChange} id="sel" style={{ marginTop: "35px" }} required>
<option>Role</option>
<option>Admin</option>
<option>Teacher</option>
<option>TeamLead</option>
</select>
</div>
<br />
<div className="col-lg-12">
{/* <Link className="nav-link" to="/"> */}
<input type="submit" name="submit" value="submit" className="btn btn-primary btn-block btn-lg" style={{ marginTop: "20px" }} />
{/* </Link> */}
</div>
</div>
</form>
</div>
</div>
<div className="col-lg-3"></div>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Adduser;

Resources