The above query has been solved but there is a new problem. I am using materialize.css for using modal and slider. Now whenever I go to the adminpage they are not working. I just show a grey screen in the slider and the modal is not getting activated. The js initialization is in my index.html which i am sharing below and the admin page which contains the modal and slider code.
index.html-
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See
https://developers.google.com/web/fundamentals/engage-and-retain/web-app-
manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css">
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root">
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-
2.1.1.min.js">
</script>
<script type="text/javascript"src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js">
</script>
<script>
$(document).ready(function () {
// the "href " attribute of .modal-trigger must specify the modal ID that wants to be triggered
$(".sidenav-trigger").sideNav();
$(".carousel").carousel();
$(".modal-trigger").leanModal();
$('.slider').slider({ full_width: true });
})
</script>
</body>
</html>
import React, { Component } from "react";
import { Link } from "react-router-dom";
import { withRouter } from "react-router-dom";
import { connect } from "react-redux";
import BillForm from "./BillForm";
import { addBill } from "../actions/Bill";
import AddBillerForm from "./AddBillerForm";
import { addBiller } from "../actions/Biller";
import Image from "../images/main.jpg";
import Image3 from "../images/Photo3.jpg";
import Footer from "./Footer";
import { fetchAdmin, adminLogout } from "../actions/Admin";
import Slider from "./Slider";
class AdminPage extends Component {
constructor(props) {
super(props);
}
componentDidMount() {
this.props.dispatch(fetchAdmin());
}
onLogout() {
this.props.dispatch(adminLogout());
this.props.history.push("/");
}
render() {
if (this.props.Admin.length < 1) {
return <div>No data</div>;
}
if (this.props.Admin.length >= 1) {
if (!this.props.Admin[0].Login) {
return <div>Not logged in as admin</div>;
}
if (this.props.Admin[0].Login) {
return (
<div>
<nav>
<div className="nav-wrapper">
<Link to="/adminpage">
<h3 className="left brand-logo">Bill Payment</h3>
</Link>
<ul className="right">
<li>
<Link className="btn-small" to="viewbiller">
View Biller
</Link>
</li>
<li>
<Link className="btn-small modal-trigger" to="#modal2">
Add Biller
</Link>
</li>
<li>
<Link className="btn-small" to="/generatedbills">
Generated Bills List
</Link>
</li>
<li>
<Link className="btn-small modal-trigger" to="#modal1">
Generate New Bill
</Link>
</li>
<li>
<button className="btn-small btn-flat teal">
Top Bill Payments
</button>
</li>
<li>
<button
className="btn-small btn-flat white-text"
onClick={e => this.onLogout()}
>
Logout
</button>
</li>
</ul>
</div>
</nav>
<div id="modal1" className="modal">
<div className="modal-content">
<div>
<p>Generate New Bill for User</p>
<BillForm
onSubmit={(bill = {}) => {
this.props.dispatch(addBill(bill));
this.props.history.push("/adminpage");
}}
/>
</div>
</div>
<div className="modal-footer red lighten-2">
<Link
to="#!"
className=" modal-action modal-close waves-effect waves-green
btn-flat"
>
Close
</Link>
</div>
</div>
<div id="modal2" className="modal">
<div className="modal-content">
<div className="">
<div className="green white-text">
<h3>Add Biller</h3>
</div>
<AddBillerForm
onSubmit={(biller = {}) => {
this.props.dispatch(addBiller(biller));
}}
/>
</div>
</div>
<div className="modal-footer red lighten-2">
<a
href="#!"
className=" modal-action modal-close waves-effect waves-green
btn-flat"
>
Close
</a>
</div>
</div>
<div>
<Slider />
</div>
<Footer />
</div>
);
}
}
}
}
const mapStateToProps = state => {
return { Admin: state.Admin };
};
export default withRouter(connect(mapStateToProps)(AdminPage));
All of your return statement are in if-statements at the moment. React always expects a return statement in the render. When none of your if-statement return true you don't have any return statement. You should add a return statement at the end of your component which returns an empty jsx element or a loading icon.
Try adding the following code on the end of your render method(should be line 127, not 100% sure): return <span> ...loading </span>
Related
I can't seem to get my browser to properly authenticate with Fortmatic and keep getting a TypeError: Cannot read property 'then' of undefined (I'm using nextjs).
I've put a button so that I can test out. Been trying to figure this out for so long now. Thank you all in advance
import Head from 'next/head'
import styles from '../styles/Home.module.css'
import Githubcorner from './components/Githubcorner'
import React from 'react'
import Fortmatic from 'fortmatic'
import Web3 from 'web3'
export default function Home() {
React.useEffect(() => {
const fm = new Fortmatic('API_Key');
window.web3 = new Web3(fm.getProvider());
console.log("window.innerHeight", window.innerHeight);
}, []);
const handleGetAccounts = () => {
web3.eth.getAccounts().then(console.log);
}
return (
<div className={styles.container}>
<Head>
<title>Monaliza</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<button
onClick={handleGetAccounts}>Random check</button>
<div className={styles.grid}>
<a
href="/Instafeedpage"
className={styles.card}
>
<h3>NFTs on The Gram →</h3>
<p>See some dope minted NFTs on the gram</p>
</a>
<a
href="/Instadroppage"
className={styles.card}
>
<h3>Drop them NFTs →</h3>
<p>Mint your own NFTs</p>
</a>
</div>
</main>
<footer className={styles.footer}>
<a href={"https://github.com"}><img src="/githublogo.png" alt="Github Icon" className={styles.logo} /></a>
<a href={"https://discord.com"}><img src="/discord.svg" alt="Discord Icon" className={styles.logo} /></a>
</footer>
</div>
)
}
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;
used HBS as Template engine in my express app. This issue come when trying to display the title in dynamic page (details page).
My Controllers
exports.getProduct = (req, res, next) => {
var prodId = req.params.productId;
Product.findById(prodId)
.then(([product]) => {
res.render('shop/product-detail', {
product: product[0],
title: product.title
});
})
.catch(err => console.log(err));
};
My Layout
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<title>{{{ title }}}</title>
</head>
My View
<div class="container">
<div class="card-deck">
<div class="card">
<img src="{{product.imageUrl}}" class="card-img-top" alt="...">
<div class="card-body">
<h5 class="card-title">{{product.title}}</h5>
<p class="card-text">{{product.description}}</p>
<p class="card-text"><small class="text-muted">Rp {{product.price}}</small></p>
<form action="/add-to-cart" method="POST">
<button type="submit" class="btn btn-outline-primary btn-block">Add to Cart</button>
<input type="hidden" name="productId" value="{{product.id}}">
</form>
</div>
</div>
</div>
</div>
In view the product title is working fine. But in the master template (layout) is not showing up.
server side : title: product[0].title
frontend side replace <title>{{{ title }}}</title> with
<title>{{ title }}</title>
Using requirejs, I can use simple routes like /register, but I always get an error when I try a nested route like /register/1 or something.
This works (where the route is just /register):
layout.js
define(['require', 'axios'], (require, axios) => {
const layout = `
<div class="container">
<div class="row">
<div class="header clearfix">
<nav style="padding-top: 10px">
<ul class="nav nav-pills pull-left">
<li role="presentation">
<h3>My App</h3>
</li>
</ul>
<ul class="nav nav-pills pull-right">
<li role="presentation">Login</li>
<li role="presentation">Register</li>
</ul>
</nav>
</div>
</div>
</div>
`;
if (window.location.pathname === '/') {
window.location.pathname = '/home'
}
axios.defaults.headers.common['authorization'] = Cookies.get('token')
return layout
})
register.js
define(['layout'], layout => {
if (window.location.pathname === '/register') {
console.log("Got it") // This works since the route is just '/register'
}
})
This does not work (where the route is /register/1):
layout.js
define(['require', 'axios'], (require, axios) => {
const layout = `
<div class="container">
<div class="row">
<div class="header clearfix">
<nav style="padding-top: 10px">
<ul class="nav nav-pills pull-left">
<li role="presentation">
<h3>My App</h3>
</li>
</ul>
<ul class="nav nav-pills pull-right">
<li role="presentation">Login</li>
<li role="presentation">Register</li>
</ul>
</nav>
</div>
</div>
</div>
`;
if (window.location.pathname === '/') {
window.location.pathname = '/home'
}
axios.defaults.headers.common['authorization'] = Cookies.get('token')
return layout
})
register.js
define(['layout'], layout => {
if (window.location.pathname === '/register/1') {
console.log("Got it") // Error
}
})
index.html
<!DOCTYPE html>
<html>
<head>
<title>My App</title>
<link
rel="stylesheet"
type="text/css"
href="/stylesheets/style.css">
<link
rel="stylesheet"
type="text/css"
href="/stylesheets/registration.css">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous">
<script
type="text/javascript"
src="/javascripts/styles/js.cookie.js">
</script>
<script data-main="config" src="require.js"></script>
<script>require(['config'])</script>
</head>
<body>
<div id="my-app"></div>
</body>
</html>
config.js
requirejs.config({
baseUrl: 'javascripts/views',
paths: {
allConversations: 'allConversations',
conversation: 'conversation',
home: 'home',
layout: 'layout',
loginView: 'login',
login: '../scripts/login',
logoutHandler: '../scripts/logout',
memberProfile: 'memberProfile',
profile: 'profile',
register: 'register',
conversationCount: 'conversationCount',
nav: 'nav',
axios: '//unpkg.com/axios/dist/axios.min',
jquery: [
'//code.jquery.com/jquery-3.3.1.min',
'//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min'
],
bootstrap: ['//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min'],
fontAwesome: ['//use.fontawesome.com/7973784de3'],
},
})
require([
'home',
'layout',
'loginView',
'login',
'logoutHandler',
'nav',
'register'
])
How do I use nested URL routes with requirejs?
First problem. You are loading config module twice. data-main attribute specifies what modules should be loaded after the RequireJS load. So the second line is basically a duplicate of this
<script data-main="config" src="require.js"></script>
<script>require(['config'])</script>
Please replace this with just
<script data-main="config" src="require.js"></script>
Second problem, you have syntax error in layout.js. Your syntax looks like JSX, not regular JavaScript. Please amend this or use RequireJS JSX files loader plugin -> https://github.com/philix/jsx-requirejs-plugin
Can you please show use you config module?
Cheers.
My slider wont come up on first time navigation of the page. However when I hard refresh the page then it comes up and also if I replace the <div ng-view></div> code with the front.html page content then also the slider starts working. Let me know what I am doing wrong in angular as I believe it is something basic that I am missing.
Following is my layout code -
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<meta charset="utf-8" />
<title>WEBSITE</title>
<link rel="stylesheet" href="assets/css/style.css" />
<link rel="stylesheet" href="assets/css/flexslider.css" type="text/css" media="screen" />
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="assets/js/jquery.js"></script>
<script src="assets/js/jquery.flexslider.js"></script>
<script src="assets/js/angular.js"></script>
<script src="assets/js/angular-route.js"></script>
<script src="controllers/mainController.js"></script>
<script>
jQuery(document).ready(function($) {
jQuery(window).load(function() {
jQuery('.flexslider').flexslider({
animation: "slide"
});
});
});
</script>
</head>
<body ng-controller="mainController">
<header ng-include="'includes/header.html'"></header>
<nav ng-include="'includes/navmenu.html'"></nav>
<div ng-view></div>
<footer ng-include="'includes/footer.html'"></footer>
</body>
</html>
Following is my main controller code -
var myApp = angular.module('myApp', ['ngRoute']);
myApp.config(function($routeProvider){
$routeProvider
.when('/', {
templateUrl: 'views/pages/front.html',
controller: 'frontCtrl'
})
});
In front.html I have slider code -
<div class="flexslider">
<ul class="slides">
<li>
<img src="assets/images/banner1.jpg">
</li>
<li>
<img src="assets/images/banner2.jpg">
</li>
<li>
<img src="assets/images/banner3.jpg">
</li>
<li>
<img src="assets/images/banner4.jpg">
</li>
</ul>
</div>
EDIT -
If I also write this code in the Firebug console then also slider starts working but not on page load -
jQuery('.flexslider').flexslider();
The event handler attached with jQuery(window).load will run when the page is fully loaded. However, ng-view hasn't loaded your view yet, which means <div class="flexslider"> doesn't exist.
Move the initialization into a directive:
myApp.directive('flexslider', function () {
return {
link: function (scope, element, attrs) {
element.flexslider({
animation: "slide"
});
}
}
});
And use like this:
<div class="flexslider" flexslider>
Demo: http://plnkr.co/edit/aVC9fnRhMkKw3xfpm4No?p=preview