× ReferenceError: Home is not defined - javascript

I wanted to import react router to my components and got the error as described in the 'title'!
btw I'm doing it from a tutorial crash course!
I will show my files below
App.js
import { BrowserRouter, Route } from "react-router-dom";
import "./App.css";
import Header from "./components/Header";
import Home from "./Pages/Home";
import About from "./Pages/About";
import Profile from "./Pages/Profile";
function App() {
return (
<BrowserRouter>
<div className="App">
<Header />
</div>
<Route path="/" component={Home} exact />
<Route path="/about" component={About} />
<Route path="/profile" component={Profile} />
</BrowserRouter>
);
}
export default App;
Home.js
const Home = () => {
return <h1>Home Page</h1>;
};
export default Home;
About.js
const About = () => {
return <h1>About Page</h1>;
};
export default About;
Profile.js
const Profile = () => {
return <h1>Profile Page</h1>;
};
export default Profile;
Header.js
const Header = () => {
return (
<>
<h1>React Router Dom</h1>
</>
)
}
export default Header;

Are you sure that it is in "./Pages/Home" ? Can you try putting Home component code above
function App()
to see if it will show the same error

Related

useParam is not working in react router Dom v6?

I am trying to pass a parameter to my other component which is productDetail component but when I am trying to access that parameter value using useParam it doesn't seems to work:
App:
import React from "react";
import { Route, Routes } from "react-router-dom";
import MainHeader from "./components/MainHeader.jsx";
import Product from "./pages/Product.jsx";
import ProductDetails from "./pages/ProductDetails.jsx";
import Welcome from "./pages/Welcome.jsx";
const App = () => {
return (
<div style={{ textAlign: "center" }}>
<header>
<MainHeader />
</header>
<Routes>
<Route path="/welcome" element={<Welcome />} />
<Route path="/product" element={<Product />} />
<Route path="/products/:productId" element={<ProductDetails />} />
</Routes>
</div>
);
};
export default App;
ProductDetailes:
import React from "react";
import { useParams } from "react-router-dom";
const ProductDetails = () => {
const params = useParams;
console.log(params.productId);
return (
<div>
<h1>Product Detail</h1>
<p>{params.productId}</p>
</div>
);
};
export default ProductDetails;
The useParams hook is a function and actually needs to be invoked in order to have any effect.
Example:
const ProductDetails = () => {
const { productId } = useParams();
useEffect(() => {
console.log({ productId });
}, [productId]);
return (
<div>
<h1>Product Detail</h1>
<p>{productId}</p>
</div>
);
};

Problem using useRoutes when redirecting with params

I am trying to set up my project for the first time using useRoutes and lazy loading with children. But I am having a problem that it won't load the children when redirected to that site? The Home page works perfectly fine.
https://codesandbox.io/s/great-rgb-ippuob?file=/src/Page/Home/index.js
Home path="/"
import React from "react";
import { Link } from "react-router-dom";
const Home = () => {
return (
<>
<h1>Hello Welcome to my beauty page</h1>
<Link to="/1">click me</Link>
</>
);
};
export default Home;
Children:
import React from "react";
import { useParams } from "react-router-dom";
const Id = () => {
const { id: loadingId } = useParams();
return <h1>Right now you are on the side of: {loadingId}</h1>;
};
export default Id;
App.js:
import "./styles.css";
import Route from "./Routes";
import { Suspense } from "react";
export default function App() {
return (
<>
<div className="App">
<Suspense fallback={<p>Loading...</p>}>
<Route />
</Suspense>
</div>
</>
);
}
Routes:
import { useRoutes } from "react-router-dom";
import React from "react";
export default function Router() {
return useRoutes([
{
path: "/",
element: <Home />,
children: [{ path: "/:id", element: <Id /> }]
}
]);
}
const Home = React.lazy(() => import("./Page/Home"));
const Id = React.lazy(() => import("./Page/Id"));
And in Index I have
<BrowserRouter>
<App />
</BrowserRouter>
You should add <Outlet /> in Layout/Parent component (Home for you)
const Home = () => {
return (
<>
<h1>Hello Welcome to my beauty page</h1>
<Link to="/1">click me</Link>
<Outlet />
</>
);
};
export default Home;

Lazy loaded routes won't show up on route change

I have two routes that I lazy load. Currently when I change route by f.e. using history.push('/') the former route disappears, but the new one won't show up (after reloading it'll show up). How so?
import React, {Suspense, lazy} from 'react';
import './App.scss';
import './modules/Header/Header.scss';
import {Route, Switch} from "react-router-dom";
import Footer from "./modules/Footer/Footer";
const LandingPage = lazy(() => import('./modules/LandingPage/LandingPage'))
const Dashboard = lazy(() => import('./modules/Dashboard/Dashboard'))
function App() {
return (
<div className="App">
<Suspense fallback={<div/>}>
<Switch>
<Route exact path='/' component={LandingPage}/>
<Route path='/dashboard' component={Dashboard}/>
</Switch>
</Suspense>
<Footer/>
</div>
);
}
export default App;
Inside of index.js I initialized Router:
...
import {Router} from 'react-router-dom';
import {createBrowserHistory} from 'history';
export const history = createBrowserHistory();
ReactDOM.render(
<React.StrictMode>
<Router history={history}>
<App/>
</Router>
</React.StrictMode>,
document.getElementById('root')
);
serviceWorker.unregister();
I would like to recommend react-loadable for code splitting dynamic imports.
With react-loadable your code should be like that:
import React from 'react';
import './App.scss';
import './modules/Header/Header.scss';
import {Route, Switch} from "react-router-dom";
import Footer from "./modules/Footer/Footer";
import Loadable from 'react-loadable'
const LoadableLandingPage = Loadable({
loader: () => import('./modules/LandingPage/LandingPage'),
loading() {
return <div>Loading...</div>
},
})
const LoadableDashboard = Loadable({
loader: () => import('./modules/Dashboard/Dashboard'),
loading() {
return <div>Loading...</div>
},
})
function App() {
return (
<div className="App">
<Switch>
<Route exact path='/' component={LoadableLandingPage}/>
<Route path='/dashboard' component={LoadableDashboard}/>
</Switch>
<Footer/>
</div>
);
}
export default App;

How to fix useEffect loader spinner problem

This is a useEffect gotcha and I run into it at least once a month. :(
Anyway,
I have a component that is rendering one of two components based on a state condition.
This works fine except for one problem. I get the infamous "flicker" render of the previous component. I am trying to mask this with a third component - dumb loader spinner. This is where the problem occurs. I can't get the dumb thing to work.
My working code is the following. The only relevant parts are those with comments.
Scroll further down for my non-working pseudo code solution.
Thank you.
import React, {useState} from 'react';
import { BrowserRouter, Route, Redirect } from "react-router-dom";
import { withRouter } from "react-router";
import {Switch} from 'react-router';
import LandingWithoutClients from './PageComponents/Landing';
import LandingWithClients from './PageComponents/Landing/LandingWithClients';
import Workflows from "./PageComponents/Workflows";
import SaveAndLoad from "./PageComponents/SaveAndLoad";
import Calendar from "./PageComponents/Calendar";
import Navbar from "./PageComponents/Navigation/Navbar";
import Authentication from './PageComponents/Authentication'
import Navigation from "./PageComponents/Navigation";
import { MuiPickersUtilsProvider } from 'material-ui-pickers';
import MomentUtils from '#date-io/moment';
import db from "./services/indexDB";
import SaveIcon from "#material-ui/icons/Save";
function App(props){
const [clientExistsState, updateClientsExistsState] = useState(false);
db.clients.toArray(function(data){
if(data[0]){
updateClientsExistsState(true)
}else{
updateClientsExistsState(false)
}
})
let Nav = clientExistsState ? Navbar : Navigation
//_____________________________________________________If clientsExists assign Landing with LandingWithClients otherwise assign Landing with LandingWithoutClients
let Landing = clientExistsState ? LandingWithClients : LandingWithoutClients
//___________________________________________________________________________________
function redirectToClientsList(){
window.location.href = "/";
}
function redirectToCalendar(){
window.location.href = "/calendar";
}
function redirectToAuthentication(){
window.location.href = "/authentication";
}
function redirectToSaveAndLoad(){
window.location.href = "/save-and-load";
}
return (
<div className="App">
<Provider>
<MuiPickersUtilsProvider utils={MomentUtils}>
<BrowserRouter>
<div>
<Nav
endpointProps = {props}
redirectToClientsList = {redirectToClientsList}
redirectToCalendar={redirectToCalendar}
redirectToAuthentication={redirectToAuthentication}
redirectToSaveAndLoad={redirectToSaveAndLoad}
/>
<Switch>
<Route exact path="/" component={Landing} /> {/* Assign Landing Component*/}
<Route exact path="/client/:id/client-name/:client/workflows" component={Workflows} />
<Route exact path="/calendar" component={Calendar} />
<Route exact path="/authentication" component={Authentication} />
<Route exact path="/save-and-load" component={SaveAndLoad} />
<Redirect from="/*" to="/" />
</Switch>
</div>
</BrowserRouter>
</MuiPickersUtilsProvider>
</Provider>
</div>
);
}
export default withRouter(App);
here is a pseudo code fix with two useEffect instances
function App(props){
// code ...
cons [ loaderBool, setLoaderBool] = useState(true);
let Landing = Loader;
useEffect(() => {
if (loaderBool) {
setTimeout(() => {
setLoaderBool(false)
},500)
}
}, [])
useEffect(() => {
if (loaderBool) {
Landing = Loader
} else {
Landing = clientExistsState ? LandingWithClients : LandingWithoutClients
}
}, [loaderBool])
return(
<div>
<Route exact path="/" component={Landing} />
</div>
)
}
I fixed it like this:
import React, {useState, useEffect} from 'react';
import { BrowserRouter, Route, Redirect } from "react-router-dom";
import { withRouter } from "react-router";
import {Switch} from 'react-router';
import LandingWithoutClients from './PageComponents/Landing';
import LandingWithClients from './PageComponents/Landing/LandingWithClients';
import Workflows from "./PageComponents/Workflows";
import SaveAndLoad from "./PageComponents/SaveAndLoad";
import Calendar from "./PageComponents/Calendar";
import Navbar from "./PageComponents/Navigation/Navbar";
import Loader from './PageComponents/Loader';
import Authentication from './PageComponents/Authentication'
import Navigation from "./PageComponents/Navigation";
import { MuiPickersUtilsProvider } from 'material-ui-pickers';
import MomentUtils from '#date-io/moment';
import db from "./services/indexDB";
import SaveIcon from "#material-ui/icons/Save";
import Context,{Provider} from "./services/context";
// if client is active display Navigation.
// if client is not active then display NavigationWitSlide
// create new landing page
function App(props){
const [loaderBool, setLoaderBool] = useState(true)
const [clientExistsState, updateClientsExistsState] = useState(false);
db.clients.toArray(function(data){
if(data[0]){
updateClientsExistsState(true)
}else{
updateClientsExistsState(false)
}
})
let Nav = clientExistsState ? Navbar : Navigation
let Landing = clientExistsState ? LandingWithClients : LandingWithoutClients
function redirectToClientsList(){
window.location.href = "/";
}
function redirectToCalendar(){
window.location.href = "/calendar";
}
function redirectToAuthentication(){
window.location.href = "/authentication";
}
function redirectToSaveAndLoad(){
window.location.href = "/save-and-load";
}
// check if clients exists
useEffect(()=>{
setTimeout(()=>{
setLoaderBool(false)
},500)
},[])
return (
<div className="App">
<Provider>
<MuiPickersUtilsProvider utils={MomentUtils}>
<BrowserRouter>
<div>
<Nav
endpointProps = {props}
redirectToClientsList = {redirectToClientsList}
redirectToCalendar={redirectToCalendar}
redirectToAuthentication={redirectToAuthentication}
redirectToSaveAndLoad={redirectToSaveAndLoad}
/>
<Switch>
<Route exact path="/" component={(function(){
if(loaderBool){
return Loader
}else{
return Landing
}
}())} />
<Route exact path="/client/:id/client-name/:client/workflows" component={Workflows} />
<Route exact path="/calendar" component={Calendar} />
<Route exact path="/authentication" component={Authentication} />
<Route exact path="/save-and-load" component={SaveAndLoad} />
<Redirect from="/*" to="/" />
</Switch>
</div>
</BrowserRouter>
</MuiPickersUtilsProvider>
</Provider>
</div>
);
}
export default withRouter(App);
Try useMemo.
const Landing = useMemo(() => {
if (!loaderBool) {
if (clientExistsState) {
return LandingWithClients;
}
return LandingWithoutClients;
}
return Loader;
}, [clientExistsState, loaderBool]);

React Components are null after default export

I just started to set up a new React project and ran into a problem and I don't have any idea how to fix it.
My static components are null after a default export. Before I seperate this into different files, all works perfectly. If I move my static AddExpense component back to my AppRoute.js file, again it still works.
What is the problem here?
import React from 'react';
const AddExpensePage = () => (
<div>
This is from my add AddExpensePage
</div>
);
export default AddExpensePage;
import {ExpenseDashBordPage} from '../components/ExpenseDashBordPage'
import {AddExpensePage} from '../components/AddExpensePage';
import {HelpPage} from '../components/HelpPage';
// import {Header2} from '../components/Header';
import React from 'react';
import {BrowserRouter, Route, Switch,NavLink} from 'react-router-dom';
const EditPage = () => (
<div>
This is the edit Page
</div>
)
const NotFoundPage = () => (
<div>
404! <NavLink to="/">Go Home</NavLink>
</div>
)
const Header =() => (
<header><h1>Expensify</h1>
<NavLink activeClassName="is-active" exact = {true} to="/">Go Home</NavLink>
<NavLink activeClassName="is-active" to="/create">create</NavLink>
<NavLink activeClassName="is-active" to="/help">Help</NavLink>
<NavLink activeClassName="is-active" to="/edit">Edit</NavLink>
</header>
);
const AppRouter = () => (
<BrowserRouter>
<div>
<Header/>
<Switch>
<Route path="/" component={ExpenseDashBordPage} exact= {true} />
<Route path="/create" component={AddExpensePage}/>
<Route path="/help" component={HelpPage}/>
<Route path="/edit" component={EditPage}/>
<Route component={NotFoundPage} />
</Switch>
</div>
</BrowserRouter>
);
export default AppRouter;
You are exporting AddExpensePage as a default export in that case you don't need to do
import {AddExpensePage} from '../components/AddExpensePage';
// this is when you are using named exports
what you need to do is refactor your import statements as this
import AddExpensePage from '../components/AddExpensePage';
// or
import {default as AddExpensePage} from '../components/AddExpensePage';

Categories

Resources