Updating properties after a callback in react - reactjs

I have the following code within Typescript React:
I am trying to set loggingIn = "true" when I get the call back from the component. This would allow the component to show an indicator that its logging in.
What is the best way to approach this?
Thank you in advance,
Marty
Login.tsx
import * as React from "react";
import * as ReactDOM from "react-dom";
import { LoginPanel } from "../Shared/LoginPanel.tsx";
let loggingIn: string = "false";
ReactDOM.render(
<LoginPanel loggingIn={ loggingIn } onLogin={
function (email:string, password:string) {
this.loggingIn = "true";
alert("Logging in with e-mail" + email + " and password " + password);
}.bind(this)
} />,
document.getElementById("loginpanel")
)
LoginPanel.tsx
import * as React from "react";
export interface Properties { loggingIn:string; onLogin: (email: string, password: string) => void; }
export class LoginPanel extends React.Component<Properties, {}> {
email: HTMLInputElement = null;
password: HTMLInputElement = null;
submit = (e: any) => {
e.preventDefault();
this.props.onLogin(this.email.value,this.password.value);
};
render() {
return <div className="row">
<div className="col-xs-3">
<h3>Log in with your email account</h3>
<form onSubmit={this.submit}>
<div className="form-group">
{ this.props.loggingIn }
<label htmlFor="email" className="sr-only">Email</label>
<input type="email" ref={(input) => { this.email = input; } } className="form-control" placeholder="somebody#example.com" />
</div>
<div className="form-group">
<label htmlFor="key" className="sr-only">Password</label>
<input type="password" ref={(input) => { this.password = input; } } className="form-control" placeholder="Password" />
</div>
<input type="submit" id="btn-login" className="btn btn-custom btn-lg btn-block" value="Log in" />
</form>
Forgot your password?
<hr />
</div>
</div>
}
}

Your Login.tsx should look like this:
let loggingIn: string = "false";
function onLogin(email: string, password: string) {
loggingIn = "true";
console.log(`logged in. email: ${ email }, password: ${ password }`);
}
ReactDOM.render(
<LoginPanel loggingIn={ loggingIn } onLogin={ onLogin } />, document.getElementById("loginpanel")
)
And the LoginPanel.tsx:
export interface Properties {
loggingIn: string;
onLogin: (email: string, password: string) => void;
}
interface State {
loggingIn: string;
}
export class LoginPanel extends React.Component<Properties, State> {
email: HTMLInputElement = null;
password: HTMLInputElement = null;
constructor(props: Properties) {
super(props);
this.state = {
loggingIn: props.loggingIn
};
}
submit = (e: React.FormEvent) => {
e.preventDefault();
this.props.onLogin(this.email.value, this.password.value);
};
render() {
return <div className="row">
<div className="col-xs-3">
<h3>Log in with your email account</h3>
<form onSubmit={ this.submit }>
<div className="form-group">
{ this.state.loggingIn }
<label htmlFor="email" className="sr-only">Email</label>
<input type="email" ref={(input) => { this.email = input; } } className="form-control" placeholder="somebody#example.com" />
</div>
<div className="form-group">
<label htmlFor="key" className="sr-only">Password</label>
<input type="password" ref={(input) => { this.password = input; } } className="form-control" placeholder="Password" />
</div>
<input type="submit" id="btn-login" className="btn btn-custom btn-lg btn-block" value="Log in" />
</form>
Forgot your password?
<hr />
</div>
</div>
}
}

Related

How do I put a form validation here so that the user must enter a name, email, and a contact number before submitting?

I'd like to make a validation so that the user would input a valid name, email and contact number before being accepted as a submission.
import React, { Component } from 'react'
import ContactService from '../services/ContactService';
class CreateContacts extends Component {
constructor(props) {
super(props)
this.state = {
id: this.props.match.params.id,
name: '',
email: '',
contact: '',
}
this.changeNameHandler = this.changeNameHandler.bind(this);
this.saveOrUpdateContact = this.saveOrUpdateContact.bind(this);
this.changeContactHandler = this.changeContactHandler.bind(this);
}
componentDidMount(){
if(this.state.id === '_add'){
return
}else{
ContactService.getContactById(this.state.id).then( (res) =>{
let contact = res.data;
this.setState({name: contact.name,
email: contact.email,
contactMain: contact.contact,
});
});
}
}
saveOrUpdateContact = (e) => {
e.preventDefault();
let contact = {name: this.state.name, email: this.state.email, contact: this.state.contact};
console.log('contact => ' + JSON.stringify(contact));
if(this.state.id === '_add'){
ContactService.createContact(contact).then(res =>{
this.props.history.push('/users');
});
}else{
ContactService.updateContact(contact, this.state.id).then( res => {
this.props.history.push('/users');
});
}
}
changeNameHandler= (event) => {
this.setState({name: event.target.value});
}
changeEmailHandler= (event) => {
this.setState({email: event.target.value});
}
changeContactHandler= (event) => {
this.setState({contact: event.target.value});
}
cancel(){
this.props.history.push('/users');
}
getTitle(){
if(this.state.id === '_add'){
return <h3 className="text-center">Add Contact</h3>
}else{
return <h3 className="text-center">Update Contact</h3>
}
}
render() {
return (
<div>
<br></br>
<div className = "container">
<div className = "row">
<div className = "card col-md-6 offset-md-3 offset-md-3">
{
this.getTitle()
}
<div className = "card-body">
<form>
<div className = "form-group">
<label> Name: </label>
<input placeholder="Name" name="name" className="form-control"
value={this.state.name} onChange={this.changeNameHandler}/>
</div>
<div className = "form-group">
<label> Email: </label>
<input placeholder="Email" name="email" className="form-control"
value={this.state.email} onChange={this.changeEmailHandler}/>
</div>
<div className = "form-group">
<label> Contact: </label>
<input placeholder="Contact" name="contact" className="form-control"
value={this.state.contact} onChange={this.changeContactHandler}/>
</div>
<button className="btn btn-success" onClick={this.saveOrUpdateContact}>Save</button>
<button className="btn btn-danger" onClick={this.cancel.bind(this)} style={{marginLeft: "10px"}}>Cancel</button>
</form>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CreateContacts

How to modify React component to use hooks?

Below is a login component without hooks. This component has two input fields and a submit button. How can we modify this component to use hooks and convert this component into a functional component that can use states?
import React from 'react';
import { userService } from '../services/user.services';
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
username: '',
password: '',
submitted: false,
loading: false,
error: ''
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(e) {
e.preventDefault();
this.setState({ submitted: true });
const data = this.state;
userService.login(data.username, data.password)
.then(
user => {
const { from } = this.props.location.state || { from: { pathname: "/" } };
this.props.history.push(from);
}
);
}
handleChange(e) {
const { name, value } = e.target;
this.setState({ [name]: value });
}
render() {
const { ...data } = this.state;
return (
<div className="login-box">
<h1>Travel With Us</h1>
<form onSubmit={this.handleSubmit}>
<div className="text-box">
<i className="fa fa-user"></i>
<input type="text" name="username" defaultValue={data.username} onChange={this.handleChange} placeholder="Username" />
</div>
<div className="text-box">
<i className="fa fa-lock" />
<input type="password" name="password" defaultValue={data.password} onChange={this.handleChange} placeholder="Passward" />
</div>
<button className="btn" value="login">Sign in</button>
</form>
</div>
);
}
}
export default Login;
Below is the sample code which I have converted to use hooks.
import React, { useState } from 'react';
import { userService } from '../services/user.services';
const LoginHooks = (props) => {
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [submitted, setSubmit] = useState(false);
let handleSubmit = function (e) {
e.preventDefault();
console.log(submitted);
setSubmit(true);
userService.login(username, password)
.then(
user => console.log(user)
);
};
return (
<div className="login-box">
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<div className="text-box">
<i className="fa fa-user"></i>
<input type="text" name="username" defaultValue={username} onChange={({target}) => setUsername(target.value)} placeholder="Username" />
</div>
<div className="text-box">
<i className="fa fa-lock" />
<input type="password" name="password" defaultValue={password} onChange={({target}) => setPassword(target.value)} placeholder="Passward" />
</div>
<button className="btn" value="login">Sign in</button>
</form>
</div>
);
}
export default LoginHooks;

React form with <Popup> alert message instead of alert()

I am trying to create a contact form in React. It sends the email. Everything is working fine. What I would like to achieve is to replace the alert('') with a better looking < Popup> message using react Popup package.
Here is the code:
import React, { Component } from 'react';
import '../css/Contact.css';
import axios from 'axios';
import Popup from "reactjs-popup";
class Contact extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
email: '',
message: '',
isValid: false
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.validationCheck = this.validationCheck.bind(this);
}
handleChange = (event) => {
const name = event.target.id;
const value = event.target.value;
this.setState ({ [name] : value});
}
validationCheck () {
if((this.state.name.length)>3 &&
(this.state.message.length)>5 &&
(this.state.email.length)>7 &&
(this.state.email.includes("#")) &&
(this.state.email.includes(".")) &&
((this.state.name || this.state.message || this.state.message)!=0)
)
{
this.setState({ isValid: true});
this.forceUpdate();
};
}
async handleSubmit (event) {
this.validationCheck();
this.forceUpdate();
if ((this.state.isValid) === true) {
event.preventDefault();
const { name, email, message } = this.state;
const form = await axios.post('/api/form', {
name,
email,
message
});
alert('thank you for your message');
event.target.reset();
}
else {
event.preventDefault();
alert('you might have entered something wrong');
}
}
render() {
return (
<div className="contact">
<h1>Contact Me</h1>
<form id="form" onSubmit={this.handleSubmit}>
<div>
<label htmlFor="Name" className="badge badge-secondary">Name</label>
<input
onChange={this.handleChange} id="name" className="form-control" placeholder="Enter your name here."/>
</div>
<div>
<label htmlFor="Email" className="badge badge-secondary">Email address</label>
<input
onChange={this.handleChange}
id="email"
className="form-control"
placeholder="Enter your e-mail address here." />
</div>
<div className="">
<label htmlFor="Message" className="badge badge-secondary">Message</label>
<textarea
onChange={this.handleChange} rows="4"
className="form-control" id="message" placeholder="Enter your message here."></textarea>
</div>
<button
type="submit"
form="form"
className="btn btn-secondary btn-lg button"
id="submit"
value="Submit"> Send! </button>
</form>
<hr />
<button type="button" className="btn btn-outline-info" onClick={this.props.scrollToTop}>
Scroll me back to the top!</button>
</div>
);
}
}
export default Contact;
I have tried to replace 'alert('thank you for your message');' with return(< Popup>); but that is clearly not a way forward.
Here's a way how you can exactly use a reactjs-popup:
import React from "react";
import Popup from "reactjs-popup";
export default () => (
<Popup trigger={<button> Trigger</button>} position="right center">
<div>Popup content here !!</div>
</Popup>
);
All you need to do is put a trigger for it and it'll work
For help: https://react-popup.netlify.com/

Getting data from SQL Server database in onClick event on React using vs2017

I am on the beginning of my programming and that's my duty to code a forum web page with login. After login I am supposed to put come content and they should be editable but I am still on the beginning. I would be really happy if someone can help because right now I need to put the data into the database (I am able to get data drom the database I can consolo them)
It is really hard coding :(
But how to get the form to the database :/
This is tsx file on frontend side.
import * as React from 'react';
import { RouteComponentProps } from 'react-router';
//import { Link, NavLink } from 'react-router-dom';
export class SignUp extends React.Component<RouteComponentProps<{}>, {}> {
constructor(props: RouteComponentProps<{}> | undefined) {
super(props);
this.state = {
name: '',
surname: '',
username: '',
email: '',
password: ''
};
this.handleNameChange = this.handleNameChange.bind(this);
this.handleSurnameChange = this.handleSurnameChange.bind(this);
}
handleNameChange(e: { preventDefault: () => void; target: { value: any; }; }) {
e.preventDefault();
this.setState({ name: e.target.value });
}
handleSurnameChange(e: { preventDefault: () => void; target: { value: any; }; }) {
e.preventDefault();
this.setState({ surname: e.target.value });
}
handleSubmit(e: any) {
e.preventDefault();
const formKayit = {
name: this.state.name,
surname: this.state.surname
};
console.log("uye oldunuz", formKayit);
}
public render() {
return (
<div>
<h1>We are glad to see you here. </h1>
<form >
<label>
Name:
<input className="form-control" type="text" onChange={(e) => { this.handleNameChange(name); }} //name="Name" value={this.state.Name} onChange={this.handleChange.bind(this)}
/>
</label>
<div>
<label>
Surname:
<input className="form-control" type="text" onChange={(e) => { this.handleSurnameChange(e); }} //name="Surname" value={this.state.Surname} onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<div>
<label>
Username:
<input className="form-control" type="text" //name="Username" value={this.state.Username} onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<div>
<label>
E-mail:
<input className="form-control" type="text" //name="Surname" value={this.state.Surname} onChange={this.handleChange.bind(this)}
/>
</label>
</div>
<label>
Password:
<input className="form-control" type="password" //name="Password" value={this.state.Password} onChange={this.handleChange.bind(this)}
/>
</label>
<div>
<button onClick={(e) => { this.handleSubmit(e); }} className="btn">SignUp </button>
</div>
</form>
</div>
);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

Account base: options.password must be a string

I looked into some similar problems and added .value. But always get error: options.password must be a string, even I cast the password.value.toString().
import React, {Component} from 'react';
import ReactDom from 'react-dom';
import { Accounts } from 'meteor/accounts-base';
class Register extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit (event){
event.preventDefault();
console.log(this.email.value);
console.log(this.password.value);
const res = Accounts.createUser(this.email.value, this.password.value.toString());
console.log(res);
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email:</label>
<input className="form-control" type="email" ref={(email) => this.email = email}/>
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input className="form-control" type="password" ref={(password) => this.password = password}/>
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">Submit</button>
</div>
</form>
);
}
}
export default Register;
You need to pass an object, not 2 string arguments:
const res = Accounts.createUser({
email: this.email.value,
password: this.password.value,
});
EDIT:
About your React component, using states and controlled components is a better practice than refs:
import React, {Component} from 'react';
import ReactDom from 'react-dom';
import { Accounts } from 'meteor/accounts-base';
class Register extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
}
this.handleSubmit = this.handleSubmit.bind(this);
}
handleInputChange(event) {
const target = event.target;
const name = target.name;
this.setState({
[name]: value,
});
}
handleSubmit (event){
event.preventDefault();
const res = Accounts.createUser({
email: this.state.email,
password: this.state.password,
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email:</label>
<input className="form-control" type="email" name="email" onChange={this.handleInputChange} />
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input className="form-control" type="password" name="password" onChange={this.handleInputChange} />
</div>
<div className="form-group">
<button type="submit" className="btn btn-primary">Submit</button>
</div>
</form>
);
}
}

Resources