I'm working on a simple login site and to navigate between Login and Sign up site I made a state called "aktivSide" meaning "activeSite" which is supposed to determine whether the login site or the sign up site will display.
Whenever I click on the "Registrer Bruker" (sign up) button, I get this error message:
Uncaught TypeError: Cannot read properties of undefined (reading 'setState')
import planB from "./plan_b.json"
import logo from './bilder/logo.png'
import './App.css';
import { FontAwesomeIcon } from '#fortawesome/react-fontawesome'
import { faEyeSlash, faEye } from '#fortawesome/free-solid-svg-icons'
import React from 'react';
class App extends React.Component {
//React
constructor(props) {
super(props);
this.state = {
aktivSide: "tom"
};
}
render() {
//JavaScript
return (
//jsx (javascript og HTML)
<>
<div onLoad={() => this.setState({ aktivSide: <LoggInn /> })} className="App">
<title>SpeedType</title>
<header className="App-header">
<div id="topp">
<img id="logoen" width={300} src={logo}></img>
</div>
<button onClick={() => console.log(this.state.aktivSide)}>state</button>
{this.state.aktivSide}
</header>
</div>
</>
)
function RegistrerBruker() {
return (
<>
<h1>Registrer Bruker</h1>
<input type="text" placeholder='brukernavn' className='input_text'></input>
<div className='passord'>
<input type="password" placeholder='passord' className='input_text'></input>
<FontAwesomeIcon className='eye_icon' id='eye_icon1' />
</div>
<p id='passordTekst'>tom</p>
<div className='knapper'>
<button className='knapper_login'><p>Logg Inn</p></button>
<button className='knapper_login'><p>Registrer deg</p></button>
</div>
</>
)
}
function LoggInn() {
//JavaScript
return (
//jsx
<>
<h1>Logg inn</h1>
<input type="text" placeholder='brukernavn' className='input_text'></input>
<div className='passord'>
<input type="password" placeholder='passord' className='input_text'></input>
<FontAwesomeIcon className='eye_icon' id='eye_icon1' />
</div>
<p id='passordTekst'>tom</p>
<div className='knapper'>
<button className='knapper_login'><p>Logg Inn</p></button>
<button onClick={() => this.setState({ aktivSide: <RegistrerBruker /> })} className='knapper_login'><p>Registrer deg</p></button>
</div>
</>
)
}
}
}
export default App;
I've tried adding:
this.aktivSide.bind(this);
to the constructor, but nothing will display.
How to show a popup modal on page load in React js functional component.basically when the page loads the popup or modal should be visible automatically without any click
Most modals will have a prop to specify whether or not the modal should be open. You can simply set this to true on initialization.
Consider an example using a Dialog from the React UI library MUI:
const SimpleDialog = (props) =>
{
const [open, setOpen] = useState(true)
return (
<Dialog open = {open}>
<DialogTitle>Title</DialogTitle>
<DialogContent>...</DialogContent>
</Dialog>
)
}
The open prop of the Dialog is based on the value of the state variable, which is initialized as true. You can change this value as needed through various Dialog actions. To learn more about MUI Dialogs, see the docs.
For information on useState, see the React docs.
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
modalState: true
};
this.handleShow = this.handleShow.bind(this);
}
handleShow() {
this.setState({ modalState: !this.state.modalState });
}
render() {
return (
<div>
<div className={"modal fade" + (this.state.modalState ? " show d-block" : " d-none")} tabIndex="-1" role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<h5 className="modal-title">My Profile</h5>
<button type="button" className="close" onClick={this.handleShow}>
<span>×</span>
</button>
</div>
<div className="modal-body">...</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" onClick={this.handleShow}>Close</button>
<button type="button" className="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
ReactDOM.render(, document.getElementById('root'));
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
I am building a nav bar with a logout button. Ideally, I would like the user to be redirected back to homepage when the log out button is being clicked. However, I am getting an error: Unhandled Rejection (TypeError): undefined has no properties when the logout button is being clicked.
Can someone kindly advice?
import React, { Component, useContext } from 'react';
import { Link, Redirect } from 'react-router-dom';
import logo from '../favicon.png';
import AuthService from '../Services/AuthServices';
import { AuthContext } from '../AuthContext';
const Navbar = props => {
const { isAuthenticated, user, setIsAuthenticated, setUser } = useContext(AuthContext);
const onClickLogoutHandler = () => {
AuthService.logout().then(data => {
if (data.success) {
setUser(data.user);
setIsAuthenticated(false);
this.props.history.push('/') }
});
}
const unauthenticatedNavBar = () => {
return (
<>
<nav className="navbar navbar-expand-sm navbar-dark bg-dark px-sm-5">
<Link to='/'>
<img src={logo} alt="store"
className='navbar-brand' />
</Link>
<ul className='navbar-nav align-item-center'>
<li className="nav-item ml=5">
<Link to="/" className="nav-link">
PRODUCTS
</Link>
</li>
</ul>
<div className="input-group">
<div className="input-group-prepend">
<div className="input-group-text" id="btnGroupAddon">#</div>
</div>
<input type="text" className="form-control" placeholder="Input group example" aria-label="Input group example" aria-describedby="btnGroupAddon" />
</div>
<ul className='navbar-nav align-item-center'>
<li className="nav-item ml-5">
<Link to="/signup" className="nav-link">
Sign Up
</Link>
</li>
<li className="nav-item ml-5">
<Link to="/login" className="nav-link">
Log In
</Link>
</li>
</ul>
<Link to='/sell' className="ml-5">
<button type='button' className="btn btn-danger">SELL</button>
</Link>
</nav>
</>
)
}
const authenticatedNavBar = () => {
return (
<>
<nav className="navbar navbar-expand-sm navbar-dark bg-dark px-sm-5">
<Link to='/'>
<img src={logo} alt="store"
className='navbar-brand' />
</Link>
<ul className='navbar-nav align-item-center'>
<li className="nav-item ml=5">
<Link to="/" className="nav-link">
PRODUCTS
</Link>
</li>
</ul>
<div className="input-group">
<div className="input-group-prepend">
<div className="input-group-text" id="btnGroupAddon">#</div>
</div>
<input type="text" className="form-control" placeholder="Input group example" aria-label="Input group example" aria-describedby="btnGroupAddon" />
</div>
<ul className='navbar-nav align-item-center'>
<li className="nav-item ml-5">
<Link to="/profile" className="nav-link">
{user.username}
</Link>
</li>
<Link to='/sell' className="ml-5">
<button type='button' className="btn btn-danger">SELL</button>
</Link>
<button type="button"
className="btn btn-link nav-item nav-link"
onClick={onClickLogoutHandler}>Logout</button>
</ul>
</nav>
</>
)
}
return (
<>
{!isAuthenticated ? unauthenticatedNavBar() : authenticatedNavBar()}
</>
)
}
export default Navbar;
Hi I need to update login name in a header after a user logs in.
this is my code:
app.componet.html
<app-header></app-header>
<router-outlet></router-outlet>
<app-footer></app-footer>
app.component.ts
import { Component,OnDestroy } from '#angular/core';
import { MyservicesService } from './myservices.service';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
constructor(private myservices: MyservicesService) {
}
}
Header.component.html
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<img class="img-responsive" src="assets/images/logo.png" alt="logo">
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li><a routerLink="home" routerLinkActive="active">Home</a></li>
<li><a routerLink="shop">Shop</a></li>
<li>About us</li>
<li>Contact</li>
<li *ngIf="displayuser" class="dropdown">
<a class="dropdown-toggle displaycurrentuser" data-toggle="dropdown" href="#">{{currentusername}}
<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a (click)="logOut()">Log out</a></li>
</ul>
</li>
<li *ngIf="!displayuser"><button style="margin-top: -10px;" class="btn btn-primary"> Login / Register</button></li>
<li><a routerLink="cartlist"><span><i class="fa fa-shopping-cart" aria-hidden="true"></i> {{noofitemsincart}} </span></a></li>
</ul>
</div>
</div>
</nav>
Header.component.ts
import { Component, OnInit,Input } from '#angular/core';
import { AuthenticationService } from '../authentication.service';
import { MyservicesService } from '../myservices.service';
#Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
displayuser:boolean = false;
currentusername;
noofitemsincart;
user:any;
constructor(private authenticationService: AuthenticationService,private myservices: MyservicesService) {
}
ngOnInit() {
this.user = this.authenticationService.getCurrentUserData();
if(this.user!=null){
//this.user=JSON.parse(this.user);
if(this.user.UserNameorEmail!=null){
this.displayuser=true;
console.log("displayuser "+this.displayuser);
this.currentusername=this.user.UserNameorEmail;
}
}
}
logOut() {
this.user= this.authenticationService.logout();
this.displayuser=false;
}
}
Loginorregistercomponent.html
<section class="news_area newsblock">
<div class="container">
<div class="row">
<div class="section-title">
<h2>my <span>account</span></h2>
</div>
</div>
<!--endrow-->
<div class="row">
<div class="col-md-6 col-sm-6 col-xs-12 spaceblock">
<div class="login">
<h3 class="titlel">Login</h3>
</div>
<form name="form" (ngSubmit)="loginform.form.valid && login()" #loginform="ngForm" novalidate>
<div class="loginpart">
<div class="form-group froma" [ngClass]="{'has-error': loginform.submitted && !username.valid}">
<label for="email">Username or email address <span class="required"> *</span></label>
<input type="email" class="form-control" id="email" placeholder="" name="username" name="username" [(ngModel)]="model.username"
#username="ngModel" required>
<div *ngIf="loginform.submitted && !username.valid" class="help-block">Username is required</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': loginform.submitted && !password.valid }">
<label for="pwd">Password<span class="required"> *</span></label>
<input type="password" class="form-control" id="pwd" placeholder="" name="password" [(ngModel)]="model.password" #password="ngModel"
required>
<div *ngIf="loginform.submitted && !password.valid" class="help-block">Password is required</div>
</div>
<div class="checkbox">
<label><input type="checkbox" name="remember"> Remember me</label>
</div>
<button [disabled]="lloading" type="submit" class="btn btn-primary">Login</button>
<img *ngIf="lloading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="
/>
<div class="lostpass">Lost your password?</div>
<div *ngIf="lerror" class="danger">{{lerror}}</div>
</div>
</form>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 spaceblock">
<div class="login">
<h3 class="titlel">Register</h3>
</div>
<form name="form" (ngSubmit)="registerform.form.valid && register()" #registerform="ngForm" novalidate>
<div class="loginpart">
<div class="form-group froma" [ngClass]="{ 'has-error': registerform.submitted && !newusername.valid }">
<label for="email">Email address <span class="required"> *</span></label>
<input type="email" class="form-control" id="email" placeholder="" name="newusername" [(ngModel)]="registermodel.newusername"
#newusername="ngModel" required>
<div *ngIf="registerform.submitted && !newusername.valid" class="help-block">Username is required</div>
</div>
<div class="form-group" [ngClass]="{ 'has-error': registerform.submitted && !newpassword.valid }">
<label for="pwd">Password<span class="required"> *</span></label>
<input type="password" class="form-control" id="pwd" placeholder="" name="newpassword" [(ngModel)]="registermodel.newpassword"
#newpassword="ngModel" required>
<div *ngIf="registerform.submitted && !newpassword.valid" class="help-block">Password is required</div>
</div>
<button type="submit" [disabled]="rloading" class="btn btn-primary">Register</button>
<img *ngIf="rloading" src="data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="
/>
<div *ngIf="rerror" class="danger">{{rerror}}</div>
</div>
</form>
</div>
</div>
<!--endimgSection-->
</div>
</section>
Loginorregistercomponent.ts
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { AuthenticationService } from '../authentication.service';
#Component({
selector: 'app-loginorregister',
templateUrl: './loginorregister.component.html',
styleUrls: ['./loginorregister.component.css']
})
export class LoginorregisterComponent implements OnInit {
model: any = {};
registermodel: any = {};
lloading = false;
rloading = false;
returnUrl: string;
lerror;
rerror;
constructor( private route: ActivatedRoute,
private router: Router,
private authenticationService: AuthenticationService) { }
ngOnInit() {
this.authenticationService.logout();
// get return url from route parameters or default to '/'
this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';
}
login() {
this.lloading = true;
this.authenticationService.login(this.model.username, this.model.password)
.subscribe(
data => {
console.log(data);
if(!data.hasOwnProperty('Code')){
this.router.navigate([this.returnUrl]);
}else{
this.lerror=data.Message;
console.log(this.lerror);
this.lloading = false;
}
},
error => {
//this.alertService.error(error);
this.lerror=error;
console.log(error);
this.lloading = false;
});
}
register() {
this.rloading = true;
this.authenticationService.create(this.registermodel.newusername, this.registermodel.newpassword)
.subscribe(
data => {
data=JSON.parse(data);
if(!data.hasOwnProperty("Code")){
this.router.navigate([this.returnUrl]);
console.log("in data "+data);
}
else{
console.log("out data "+data.Message);
this.rerror=data.Message;
this.rloading = false;
}
},
error => {
// this.alertService.error(error);
this.rerror=error;
this.rloading = false;
});
}
}
authenticationService.ts
import { Injectable } from '#angular/core';
import { Http, Headers, RequestOptions, Response } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
#Injectable()
export class AuthenticationService {
user:any;
headers = new Headers({ 'Content-Type': 'application/json' });
options = new RequestOptions({ headers: this.headers });
constructor(private http: Http) { }
login(username: string, password: string) {
return this.http.post('http://www.myweb.com/User/Login', JSON.stringify({UserNameorEmail: username,Password: password}),this.options)
.map((response: Response) => {
let user = response.json();
console.log("in service "+user);
if (user) {
localStorage.setItem('currentUser', JSON.stringify(user));
console.log("user.token "+user);
}
return user;
});
}
logout() {
// remove user from local storage to log user out
localStorage.removeItem('currentUser');
}
create(username: string, password: string) {
return this.http.post('http://www.myweb.com/User/Add', JSON.stringify({UserNameorEmail: username, Password: password }),this.options)
.map((response: Response) => {
let user = response.json();
if (user) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
return user;
});
}
getCurrentUserData(){
this.user= localStorage.getItem("currentUser");
this.user=JSON.parse(this.user);
if(this.user!=null){
if(this.user.UserNameorEmail!=null){
return this.user;
}else{
return this.user=null;
}
}else{
return this.user=null;
}
}
}
I typically have a state.service.ts in my projects in which I store application state (current user etc.)
In this, I create the following:
// BehaviorSubject to store UserName
private currentUserNameStore = new BehaviorSubject<string>("");
// Make UserName store Observable
public currentUserName$ = this.currentUserNameStore.asObservable();
// Setter to update UserName
setCurrentUserName(userName: string) {
this.currentUserNameStore.next(userName);
}
Then in the header component where you need to display the current User, you subscribe to the Observable from your state service:
stateSvc.currentUserName$
.subscribe(
userName => {
userName = userName;
});
And you can display this in the header like this:
{{userName}}
Then in your login component, once you've got a logged in user, you set the value using the Setter in the service:
this.stateSvc.setCurrentUserName(this.userName);
As the Title on the header component is subscribed, it will pickup the changes and update the display on the component.
You have to check authenticity of user before loading <app-header> </app-header>
i.e.
<div *ngIf="authorised">
<app-header></app-header>
</div>
where authorised is a member of app.component.ts.
i.e. You have to make sure if displayuser or currentusername is available before rendering <app-header></app-header>.
Please mark if you find it helpful.
I'm newbie with Aurelia and frontend frameworks generally.
I have page with List
list.html
<template>
<require from="services/list-item"></require>
<div class="container-fluid">
<div class="row row-centered container-top-space">
<div repeat.for="item of items">
<list-item item.bind="item"></list-item>
</div>
</div>
</div>
</template>
list.js
import { inject } from 'aurelia-framework';
import { HttpClient, json } from 'aurelia-fetch-client';
#inject(HttpClient)
export class ListItem{
constructor(httpClient) {
this.items= [];
httpClient.configure(...);
}
}
and ListItem
list-item.html
<template>
<div class="row">
<div class="list-item">
<div class="form-control-inline" style="width:33%">
<span>${item.name} </span>
</div>
<div class="form-control-inline" style="width:54%">
<span>${item.value}</span>
</div>
<div class="pull-right" style="width:100px">
<button class="btn btn-list-item" type="submit" name="submit" click.delegate="edit($event.target.parentElement)">Edit</button>
</div>
</div>
</div>
</template>
list-item.js
import { bindable } from 'aurelia-framework';
export class ListItem{
#bindable item;
edit(element){
//I'd like to replace view component with update component here
}
}
I'd like to change template of list-item on list-item-edit when edit function will be called, but completely don't know how to make it.