Trying to call a function in React - javascript

I have a java script file called Toolbar.js in which I am trying to call a function that is in my App.js file as the following:
<DrawerToggleButton click={props.drawerClickHandler}/>
The above does not work, it shows "Unresolved variable drawerClickHandler" which I assume means that Toolbar.js can not see the functions in App.js. I have tried this without using props with no results. How can I get this to work?
Also just want to state the program will build and run with no errors, just that the button I am trying to map the function to, does nothing when I click it.
Code below:
Toolbar.js:
import React from 'react';
import './Toolbar.css';
import DrawerToggleButton from '../SideDrawer/DrawerToggleButton'
import '../SideDrawer/DrawerToggleButton';
import sideDrawer from "../SideDrawer/SideDrawer";
const toolbar = props =>(
<header className="toolbar">
<nav className="toolbar_navigation">
<div>
<DrawerToggleButton click={props.drawerClickHandler}/>
</div>
<div className="toolbar_logo">Kleen Portal</div>
<div className="spacer" />
<div className="toolbar_navigation-items">
<ul>
<li>Logout</li>
</ul>
</div>
</nav>
</header>
);
export default toolbar;
App.js:
import React, { useState, useEffect } from "react";
// import logo from './logo.svg';
import './App.css';
import Routes from "./Routes";
import { Auth } from "aws-amplify";
import { Link, withRouter } from "react-router-dom";
// import { Navbar } from "react-bootstrap";
import Toolbar from './components/Toolbar/Toolbar';
import SideDrawer from './components/SideDrawer/SideDrawer';
import Backdrop from './components/Backdrop/Backdrop';
function App(props) {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const [isAuthenticating, setIsAuthenticating] = useState(true);
const [sideDrawerOpen, setIsSideDrawerOpen] = useState(false);
useEffect(() => {
onLoad();
}, [isAuthenticating, isAuthenticated]);
async function onLoad() {
try {
await Auth.currentSession();
setIsAuthenticated(true);
props.history.push("/dashboard");
}
catch(e) {
alert(e);
}
setIsAuthenticating(false);
}
function handleLogout() {
setIsAuthenticated(false);
props.history.push("/login");
}
function drawerToggleClickHandler(){
setIsSideDrawerOpen(!sideDrawerOpen)
}
let sideDrawer;
let backdrop;
let toolBar;
if(isAuthenticated){
toolBar = (
<Toolbar
handleLogout={handleLogout}
drawerClickHandler ={drawerToggleClickHandler}
/>
)
}
if (isAuthenticated && sideDrawerOpen){
sideDrawer = <SideDrawer/>;
backdrop = <Backdrop/>
}
return (
<div className="App container" style={{height: '100%'}}>
{toolBar}
{sideDrawer}
{backdrop}
{/*<Toolbar/>*/}
{/*<SideDrawer/>*/}
{/*<Backdrop/>*/}
<Routes appProps={{ isAuthenticated, setIsAuthenticated }} />
</div>
);
}
export default withRouter(App);
DrawerToggleButton.js:
import React from 'react';
import './DrawerToggleButton.css'
const drawerToggleButton = props => (
<button className="toggle-button" onClick={props.click}>
<div className="toggle-button_line" />
<div className="toggle-button_line" />
<div className="toggle-button_line" />
</button>
);
export default drawerToggleButton;

Related

Video taking too long to load react

I have a video which plays on a loop on the landing page. It takes sometime for it to load. I also have a custom spinner (SpinnerComponent) which I want to play while the video is getting loaded:
import React, { useEffect, useState } from "react";
import NavbarComponent from './Components/Navbar/navbar';
import AboutComponent from './Components/About/about';
import HealthComponent from './Components/Health/health';
import SpinnerComponent from './Components/Spinner/spinner';
import LandingComponent from './Components/Landing/landing';
import ContactUs from './Components/ContactUs/contactUs';
import Footer from './Components/Footer/footer';
function App() {
return (
<>
<NavbarComponent/>
<LandingComponent/>
<AboutComponent/>
<HealthComponent/>
<ContactUs/>
<Footer/>
</>
);
}
export default App;
Landing Component
import React, {useEffect} from 'react'
import './styleLanding.css';
import AOS from 'aos';
import 'aos/dist/aos.css';
import sample from '../../videos/movie.mp4'
export const LandingComponent = () => {
useEffect(() => {
AOS.init();
}, [])
return (
<div id="home" className="style-landing" >
<div className="style-overlay"></div>
<video src={sample} type={'video/mp4'} preload={'auto'} className="style-video" autoPlay loop muted/>
<div className="style-content">
<h2 className="style-heading" data-aos="zoom-in" data-aos-duration="1000" data-aos-offset="130">EXPERIENCE THE BEST</h2>
<h1 className="style-sub-heading" data-aos="zoom-in" data-aos-duration="1000" data-aos-offset="130">nutrition</h1>
</div>
</div>
)
}
export default LandingComponent
How can I modify it such that the spinner component plays on the entire screen (without the navbar) and only once the video is done loading, I can show the entire webpage?
Thanking in advance!
App.js:
import React, { useEffect, useState } from "react";
import NavbarComponent from './Components/Navbar/navbar';
import AboutComponent from './Components/About/about';
import HealthComponent from './Components/Health/health';
import SpinnerComponent from './Components/Spinner/spinner';
import LandingComponent from './Components/Landing/landing';
import ContactUs from './Components/ContactUs/contactUs';
import Footer from './Components/Footer/footer';
function App() {
const [loaded, setLoaded] = useState(false);
useEffect(() => {
const video = document.getElementById('landing-video');
video.addEventListener('load', () => {
setLoaded(true);
});
}, []);
return (
<>
{loaded ? (
<>
<NavbarComponent/>
<LandingComponent/>
<AboutComponent/>
<HealthComponent/>
<ContactUs/>
<Footer/>
</>
) : (
<SpinnerComponent fullscreen={true} />
)}
</>
);
}
export default App;
LandingComponent.js:
import React, {useEffect, useRef, useState} from 'react'
import './styleLanding.css';
import AOS from 'aos';
import 'aos/dist/aos.css';
import sample from '../../videos/movie.mp4'
export const LandingComponent = () => {
const [loaded, setLoaded] = useState(false);
const videoRef = useRef(null);
useEffect(() => {
AOS.init();
const video = videoRef.current;
video.addEventListener('canplaythrough', () => {
video.play();
setLoaded(true);
});
}, [])
return (
<div id="home" className="style-landing" >
<div className="style-overlay"></div>
<video ref={videoRef} id="landing-video" src={sample} type={'video/mp4'} preload={'auto'} className="style-video" autoPlay loop muted hidden={!loaded} />
<div className="style-content">
<h2 className="style-heading" data-aos="zoom-in" data-aos-duration="1000" data-aos-offset="130">EXPERIENCE THE BEST</h2>
<h1 className="style-sub-heading" data-aos="zoom-in" data-aos-duration="1000" data-aos-offset="130">nutrition</h1>
</div>
</div>
)
}
export default LandingComponent

Modal Content isn't rendering while the Backdrop is - can't figure out the error

I am trying to implement a cart as a Modal on my project. The issue is that the Backdrop is rendering as it should but the Overlay isn't. It has been 30 minutes but I can't figure out the error, attaching the files below.
For now, the Modal should render all the time according to the code as I have yet to implement the conditional rendering but that isn't an issue, the issue is that the Overlay isn't showing up for some reason.
App.js file
import "./App.css";
import { useState } from "react";
import Middlebar from "./Components/Middlebar";
import FilterTab from "./Components/FilterTab";
import ProductPage from "./Components/ProductPage";
import Navbar from "./Components/Navbar";
import { Route, Switch } from "react-router-dom";
import Data from "./Components/data.json";
import ProductDetail from "./pages/ProductDetail";
import Cart from "./Components/Cart";
function App() {
const [searchedTerm, setSearchedTerm] = useState("");
const getSearchTerm = (term) => {
setSearchedTerm(term);
};
return (
<Switch>
<Route path="/" exact>
<Navbar onSearch={getSearchTerm} />,
<Cart/>,
<Middlebar />,
<div className="filter-product row">
{" "}
<FilterTab></FilterTab>{" "}
<ProductPage searchTerm={searchedTerm}></ProductPage>{" "}
</div>
</Route>
<Route path="/product/:id">
<ProductDetail></ProductDetail>
</Route>
</Switch>
);
}
export default App;
Modal.js file
import { Fragment } from "react";
import ReactDOM from "react-dom";
import "./Modal.css";
const Backdrop = (props) => {
return <div onClick = {props.onClick} className="backdrop"></div>;
};
const ModalOverlay = (props) => {
return (
<div className="modal">
<div className="content">{props.children}</div>
</div>
);
};
const portalElement = document.getElementById("overlays");
export default function Modal(props) {
return (
<Fragment>
{ReactDOM.createPortal(<Backdrop />, portalElement)}
{ReactDOM.createPortal(
<ModalOverlay>{props.children}</ModalOverlay>,
portalElement
)}
</Fragment>
);
}
Cart.js file
import React from "react";
import Modal from "../Modal";
import "./Cart.css";
export default function Cart() {
return (
<Modal>
<div className="total">
<span>Total</span>
<span>hi</span>
</div>
<div className="actions">
<button className="button--alt">
Close
</button>
<button className="button">Order</button>
</div>
</Modal>
);
}

how to use setTimeout on a react component

This question might be simple to most web developers but I am pretty new and cannot figure out the way to put a settimeout function on what I would like to show on a page. below is the example of the code I would like to add a timeout for.
import React from "react";
function Navbar() {
return (
<div className="navbar">
<h4>
Contact
</h4>
<h4>About Me</h4>
</div>
);
}
export default Navbar;
and here is my app.jsx which then will be exported to be used in index.js . What I want is to have lets say 5s delay before my Navbar function shows.
import React, { useEffect } from "react";
import Navbar from "./Navbar";
import Contact from "./Contact";
function App() {
return (
<div>
<Navbar />
<Contact />
</div>
);
}
export default App;
You can add setTimeout in your App Component. It should look like this:
import React, { useState, useEffect } from "react";
import Navbar from "./Navbar";
import Contact from "./Contact";
function App() {
const [showNavBar, setShowNavBar] = useState(false);
useEffect(() => {
const timer = setTimeout(() => {
setShowNavBar(true);
}, 5000);
return () => clearTimeout(timer);
}, [])
return (
<div>
{showNavBar ? <Navbar /> : null}
<Contact />
</div>
);
}
export default App;
your can add a state 'loading' and add useEffect hook and then use setTimeout there and change the loading state to false after 5seconds. in return section all you need to do is check if loading is false you show the otherwise it will show nothing.
import React, { useEffect, useState } from "react";
import Navbar from "./Navbar";
import Contact from "./Contact";
function App() {
const [loading, setLoading] = useState(true);
useEffect(() => {
setTimeout(() => {
setLoading(false);
}, 5000);
}, [])
return (
<div>
{!loading && <Navbar /> }
<Contact />
</div>
);
}
export default App;

How to redirect to another page in react

I have two buttons in my code, each trying a different way for redirecting, in one of them i'm trying to use <a>, and the other one I'm trying to use route, but none of them seem to work.
Here's my code:
Component DefineDestino.js:
import React, {useState} from "react"
import { Link, BrowserRouter, Routes, Route } from "react-router-dom"
import CheckOut from "../CheckOut"
export default function DefineDestino(props) {
const [initialValue, setValue] = useState(0)
const increment = () => {
return {
type:'counter/increment'
}
}
function estadosReducer(state, action) {
if (state === 'Rio de Janeiro' && action.type === 'counter/increment') {
setValue(initialValue + 1000)
}
}
return(
<div>
<h1>Valor: {initialValue}</h1>
<button onClick={() => estadosReducer(props.data, increment())}>Efetuar Compra</button>
</div>
)
}
App.js:
import Origem from './components/Origem';
import Destino from './components/Destino'
import './styles/App.css';
import React, {useState} from "react"
import EstadosOrigem from './components/Origem';
import EstadosDestino from './components/Destino';
import DefineDestino from './components/DefineDestino';
import { Link, BrowserRouter as Router, Routes, Route, Switch } from "react-router-dom";
import CheckOut from './CheckOut';
function App() {
return (
<Router>
<div className="App">
<div className="mainContent">
<h1>Escolha um destino.</h1>
< EstadosOrigem ></EstadosOrigem>
< EstadosDestino ></EstadosDestino>
<Routes>
<Route path="/CheckOut" component={CheckOut}></Route>
</Routes>
</div>
</div>
</Router>
);
}
export default App;
The page I'm trying to redirect to CheckOut.js:
function CheckOut() {
return (
<div className="CheckOut">
<div className="mainContent">
<h1>TESTE.</h1>
</div>
</div>
);
}
export default CheckOut;

Passing a function

Still learning Java and functions. Was writing some code but got stumped.
In my App.js class, I have a line of code in the return statement as follows:
<Toolbar drawerClickHandler ={props.drawerToggleClickHandler}/>
In my Toolbar class, it would activate via a "click" as follows:
<DrawerToggleButton click={props.drawerClickHandler}/>
Which would last be connected to another class DrawerToggleButton in the following code:
<button className="toggle-button" onClick={props.click}>
The Toolbas class and the DrawerToggleButton have no issues with passing but props.drawerToggleClickHandler does not work, says "Unresolved variable drawerToggleClickHandler".
How can I fix this? Full code below:
App.js:
import React, { useState, useEffect } from "react";
// import logo from './logo.svg';
import './App.css';
import Routes from "./Routes";
import { Auth } from "aws-amplify";
import { Link, withRouter } from "react-router-dom";
// import { Navbar } from "react-bootstrap";
import Toolbar from './components/Toolbar/Toolbar';
import SideDrawer from './components/SideDrawer/SideDrawer';
import Backdrop from './components/Backdrop/Backdrop';
function App(props) {
const [isAuthenticated, userHasAuthenticated] = useState(false);
const [isAuthenticating, setIsAuthenticating] = useState(true);
const [sideDrawerOpen, setIsSideDrawerOpen] = useState(false);
useEffect(() => {
onLoad();
}, []);
async function onLoad() {
try {
await Auth.currentSession();
userHasAuthenticated(true);
}
catch(e) {
if (e !== 'No current user') {
alert(e);
}
}
setIsAuthenticating(false);
}
function handleLogout() {
userHasAuthenticated(false);
props.history.push("/login");
}
function drawerToggleClickHandler(){
if(sideDrawerOpen){
return {setIsSideDrawerOpen: false};
}
else{
return {setIsSideDrawerOpen: true};
}
}
let sideDrawer;
let backdrop;
let toolBar;
if(userHasAuthenticated === true){
toolBar = <Toolbar drawerClickHandler ={props.drawerToggleClickHandler}/>
}
if (userHasAuthenticated === true && sideDrawerOpen === true){
sideDrawer = <SideDrawer/>;
backdrop = <Backdrop/>
}
return (
<div className="App container" style={{height: '100%'}}>
{toolBar}
{sideDrawer}
{backdrop}
{/*<Toolbar/>*/}
{/*<SideDrawer/>*/}
{/*<Backdrop/>*/}
<Routes appProps={{ isAuthenticated, userHasAuthenticated }} />
</div>
);
}
export default withRouter(App);
Toolbar.js:
import React from 'react';
import './Toolbar.css';
import DrawerToggleButton from '../SideDrawer/DrawerToggleButton'
import '../SideDrawer/DrawerToggleButton';
import sideDrawer from "../SideDrawer/SideDrawer";
const toolbar = props =>(
<header className="toolbar">
<nav className="toolbar_navigation">
<div>
<DrawerToggleButton click={props.drawerClickHandler}/>
</div>
<div className="toolbar_logo">Kleen Portal</div>
<div className="spacer" />
<div className="toolbar_navigation-items">
<ul>
<li>Logout</li>
</ul>
</div>
</nav>
</header>
);
export default toolbar;
DrawerToggleButton.js:
import React from 'react';
import './DrawerToggleButton.css'
const drawerToggleButton = props => (
<button className="toggle-button" onClick={props.click}>
<div className="toggle-button_line" />
<div className="toggle-button_line" />
<div className="toggle-button_line" />
</button>
);
export default drawerToggleButton;
You're not changing state: you'd need to change your function to this (and i'd suggest renaming setState to setsIsSideDrawerOpen)
function drawerToggleClickHandler(){
if(sideDrawerOpen){
setState(false)
}
else{
setState(true)
}
}
Change
toolBar = <Toolbar drawerClickHandler ={props.drawerToggleClickHandler}/>
to
toolBar = <Toolbar drawerClickHandler ={drawerToggleClickHandler}/>
drawerToggleClickHandler is not a prop
[Also app.js is not a class it's a functional component]
to answer your second comment question I wouldn't event assign your component to a variable, just do it inline:
<div className="App container" style={{height: '100%'}}>
{userHasAuthenticated && <Toolbar drawerClickHandler =props.drawerToggleClickHandler}/>
}
...

Categories