Is possible render multicomponents after trigged a function in vuejs? - javascript

For example, I created a Root Component named Index.vue, and Registred these 3 Login, Agree and Validation. What I'm picturing out is, after click submit button inside Login, the Agree.vue is showed and successively is happen when I click submit button inside Agree.
I think that I should use prop data to passing among components a state about each components, that way trigged a command to show the component that I want. But how I should "hide" the other components. I don't know if there a way to register the component at the moment submit form inside each Login, Agree, ...
<template>
<v-app>
<Login />
<Agree />
<Validation />
</v-app>
</template>
<script>
export default {
components:{
Login: () => import('./components/Login'),
Agree: () => import('./components/Agree-Term')
Validation: () => import('./components/Validation')
}
}
</script>

Related

Submit button reloads the page

I am working on a login form, and I am getting a strange behavior whereby whenever I click on the 'Login' button, the page simply reloads, without logging in my email and password through the 'submitHandler' function.
Below is a code of the form (I removed a lot of extra CSS formatting and div's).
Here is a screenshot of the form:
loginForm
import React from 'react'
import { useState, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { login } from "../../../actions/userActions";
import { Form, Button, Row, Col } from "react-bootstrap";
function LoginForm ({history}) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const submitHandler = (e) => {
e.preventDefault();
console.log(email, password)
// dispatch(login(email, password));
};
return (
<form>
<button onSubmit={submitHandler} type="submit">
Login
</button>
</form>
)
}
export default LoginForm
Does anyone have idea why the page reloads after clicking on the login button?
Issue
The button is of type="submit" but the form has no onSubmit handler and is thus taking the default form action, i.e. submitting the form and reloading the page.
Solution
Move the onSubmit to the form element so the callback can prevent the default form action from occurring.
<form onSubmit={submitHandler}>
<button type="submit">
Login
</button>
</form>
You can also convert button type="" method provider submit to button, in some cases you don't really want to submit internal form so just keep in mind.
Here is the example,
<form>
<button onSubmit={submitHandler} type="button">
</form>
Other answer is also OK, but I would like to approach from a different angle.
Try calling the submitHandler with onSubmit on the form instead of on the button.

how to return a logout validation message on button click in react js

I have a react component
const Header = () => {
return(
<div role="button" className="user-logout" onClick={logoutUser}>
<i className="fas fa-sign-out-alt user--nav--icon"></i>
Logout
</div>
)}
In the above code onClick logout the user gets logged out
const logoutUser = () => {
dispatch(logout());
history.push('/login');
};
but I want the user to get a message popup onClcik in a div with conforming logout or cancel
and then on confirming logout it should logout the user
You can pass a GET Parameter to the login page like:
history.push('/login?logout=1');
Then if the login page has this parameter, render your message.
If you don't want to use a parameter, you will have to look for another solution either with react context or react navigation

React: Firebase auth function calls by itself when the component renders

GOAL:
I am making a login by Google functionality in my website using Firebase Auth. I want When the user clicks the Signin link in the Navbar, he is redirected to the login page, in the login page, there is a dummy email/password input form and a Login with Google Button. When the user clicks on the Login with Google button he should be redirected to all the email list, so that he can choose from which he wants to login.
ERROR:
When the user clicks on the Signin Link in the Navbar the Login Route opens up and the function for the firebase auth is called by itself, without even clicking the Google Signin Button and the user is redirected to the emails list page.
Login.jsx:
import React from 'react'
import {Link} from "react-router-dom"
import './components/css/login.css'
import googleLogo from "./components/svg/google.svg"
import brandLogo from "./components/img/logo1.png"
//The JS for Login is in another file
import { googleSignin } from './firebase/googleLogin'
function login() {
return (
<div className="background-div" >
<nav className="login-nav" >
<img src={brandLogo} alt="logo"/>
<h2>the<strong>Dukaandar</strong></h2>
</nav>
<form action="" className="login-form">
<h3><strong>Login into your account</strong></h3>
<h5 className="login-email" >Email</h5>
<input type="text" className="login-email-input" placeholder="Enter your email" />
<h5 className="login-password">Password</h5>
<input type="password" className="login-password-input" placeholder="Enter your password" />
<br />
<button className="login-button">Login</button>
<Link className="login-forgot-password">forgot password?</Link>
<hr />
// The onClick attribute in React, I expect anything to happen only after clicking this button
<button className="google-login" onClick={googleSignin()} > <span className="google-image"><img src={googleLogo} alt=""/></span>Login with Google</button>
<Link to={"/"}>Back to Home</Link>
</form>
</div>
)
}
export default login
JS File:
import firebase from 'firebase'
const firebaseConfig = {
// Key value pairs of my config
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
//This is the Function which has to be called on button click
function googleSignin() {
var provider = new firebase.auth.GoogleAuthProvider();
firebase
.auth()
.signInWithRedirect(provider)
.then(function(result) {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
// The signed-in user info.
var user = result.user;
console.log(user);
console.log(result);
})
.catch(function(error) {
console.log(error);
});
}
export { googleSignin }
While searching for it I came to know about lifecycle methods which occurs when the component is rendered, if that is the case here, how to stop them to call itself?
As told in answer below and from my finding onClick{ () => googleSignin } also does not work, and also when I call the function with parenthesis googleSignin(), the function is atleast called but withot it nothing hapens.
I suspect there can be a React Router problem also, but I don't know.
Thank you in advance
Full Source Code of the Website on Github,
Live Preview on Netlify
By adding parenthesis on the onClick handler, you are invoking the function as soon as it is loaded. Remove the parenthesis and it will work.
<button className="google-login" onClick={googleSignin}>
<span className="google-image">
<img src={googleLogo} alt="" />
</span>
Login with Google
</button>
When the Browser sees the function is being called and not referenced on the OnClick method, it takes the responsibility and calls the function by itself. So, we have to free the Browser from its responsibility, and let the Function to be called only when the User clicks on the button.
Make a Handler function to free the Browser from its responsibility:
function handleClick(e) {
e.preventDefault();
googleSignin();
console.log('The link was clicked.');
}
Reference handleClick in your onClick method:
<button className="google-login"
//Reference handleClick here.
onClick={handleClick}>
<span className="google-image">
<img src={googleLogo} alt=""/>
</span>
Login with Google
</button>
This will solve the problem.

Angular2 Form : trigger or update validation properly & programmatically

I'm building a Wizard in Angular2 - Redux. I'm using Reactive Forms to handle & submit data for every step inside. I need to trigger form validation programmatically, because the declaration of my call-to-action button, in order to go to the next step, is in a separated component from the stepComponent. See wireframe below
Components's wireframe
Current Behavior
Only when a change has ocurred on a form's control, its own validation
runs. And it's touched & valid property is updated accordingly.
As I am in a Redux environment, I dispatch an action to get the
current-step form data in order to be applied to the payload. When
that's is finished, I trigger another action to save data.
Actually, I know when the form is valid or invalid by using:
submitForm(form: FormGroup):void{
if(form.valid){
this.actionsStep.saveStep(form.value);
}else{
console.log('Form invalid ')
}
}
As my forms uses controls's properties to render a custom message
when a error has happened, I want to re-run validation
by submit the form or by using another function to be able to use
the control's properties again to notify where an error has occurred.
StepComponent.ts : Form declaration
this.stepForm = this.formBuilder.group({
name: ['', Validators.required],
email: ['', Validators.required]
});
step-component.html : Form HTML
<form id="ngForm" [formGroup]="stepForm" (ngSubmit)="submitForm(stepForm.value)" class="form-horizontal form-box-content">
<div class="form-group row" [ngClass]="{'has-danger' :name.invalid && name.touched}">
<label class="col-md-2 col-form-label">Name:</label>
<div class="col-md-10">
<input
name="titulo" class="form-control required"
formControlName="name" placeholder="" type="text" [ngClass]="{'form-control-danger' :name.invalid && name.touched}" >
<small class="form-control-feedback text-danger" *ngIf="name.invalid && name.touched && name.hasError('required')">
The name is required
</small>
</div>
</div>
Attemps
I tried to use
Update Validity:
this.stepForm.updateValueAndValidity();
Update Validity providing params:
this.stepForm.updateValueAndValidity({ onlySelf: false, emitEvent: true });
Mark each control as touched (To trigger event as I've typed something)
for (var i in this.stepForm.controls) {
this.stepForm.controls[i].markAsTouched();
}
The solutions which requires submit function to be called from the HTML
will not work for me because the button and the form are in separated components.
5. Is there any way to trigger or update validation programmatically or at least to submit a form properly in a function?
Previous Research
I found many help links to achieve this, however,those solutions work only when the button is declared in the same component. And also, when button is inside the form tag:
Angular2 - Validate and submit form from outside : Work only in
the same component
angular2 validate form on button click : Work only in the same component
Angular 2 Submit button outside of form : Not working
Is there a way to
submit an Angular 2 model-driven form (reactive form) from a outside
button? : Refers to previous link
I basically had the same setup, and got around it by doing the equivalent of
(this.stepForm as any).submitted = true
In case someone else is still trying to do this. I did this by using ViewChild to grab references to the referenced components and stepper. Then control the next button click and do not have matStepperNext on the button.
<button mat-button (click)="onStepOneNextClick()">Next</button>
#ViewChild(MatStepper) stepper: MatStepper;
#ViewChild(StepOneComponent, { static: true }) stepOneComponent: StepOneComponent;
onStepOneNextClick() {
if (this.stepOneComponent.form.invalid) {
this.stepOneComponent.form.markAllAsTouched();
}
else {
this.stepper.next();
}
}

Rendering a new class in react

I want a way to show a classes render method due to an onclick event.
I have a log in page, once the uses completes it and hits submit (aka logs in), I want a new view to render.
class LoginPage extends React.Component{
render() {
return (
<div id="container">
<button onClick={() => this.refs.myref.myfunc()}>Click</button>
<form onSubmit={this.handleClick}>
<p><input type="text" id="playerName" value={this.props.nameValue} onChange={this.handleNameChange} /></p>
<p><input type="email" id="playerEmail" value={this.props.emailValue} onChange={this.handleEmailChange}/></p>
<p><input type="submit" value="submit" /></p>
</form>
</div>
)
}
}
class HomePage extends React.Component{
//does things
render() {
return (
<div>
<h1 className="headings" id="heading"> Home Page </h1>
</div>
)
}
}
How can I render the Home Page title instead of the form. I used to have some code that would toggle it based on state but now I am trying to break it into components and only set state in one place.
The handleClick function was updating the state before but now it is doing nothing but I want it to in some way call the render method inside the homepage component or pass state/props around. what is the react way of doing this? can further clarify if things do not make sense

Categories

Resources