React js cannot change page - javascript

I am learning react js and have a simple webpage with a few different views, and then a few different pages. I can change between the views just fine, but when I try to go to a page (in this case the login page, but the other have the same issue) the url path changes and the default landing page is viewed instead. The default page when loading the website is: http://localhost:3000/#/dashboard
If I press the login button, the code is:
<CButton
onClick={async () => {
window.location.href = "/login";
}}
>
<CIcon icon={cilUser} className="me-2" />
Login
</CButton>
Then it should redirect me to the /login page, but instead I get redirected to: http://localhost:3000/login#/dashboard
Why is this?
This is my App.js
import React, { Component, Suspense, useState, useMemo } from "react";
import { HashRouter, Route, Switch, withRouter } from "react-router-dom";
import "./scss/style.scss";
import { UserContext } from "./UserContext";
import { getProtectedAsset } from "./getProtectedAsset";
const loading = (
<div className="pt-3 text-center">
<div className="sk-spinner sk-spinner-pulse"></div>
</div>
);
// Containers
const DefaultLayout = React.lazy(() => import("./layout/DefaultLayout"));
// Pages
const Login = React.lazy(() => import("./views/pages/login/Login"));
const Page404 = React.lazy(() => import("./views/pages/page404/Page404"));
const Page500 = React.lazy(() => import("./views/pages/page500/Page500"));
function App() {
const [user, setUser] = useState({
userID: -1,
});
const value = useMemo(() => ({ user, setUser }), [user, setUser]);
return (
<UserContext.Provider value={value}>
<HashRouter>
<React.Suspense fallback={loading}>
<Switch>
<Route
exact
path="/login"
name="Login"
render={(props) => <Login {...props} />}
/>
<Route
exact
path="/register"
name="Register Page"
render={(props) => <Register {...props} />}
/>
<Route
exact
path="/register_club"
name="Register Club Page"
render={(props) => <Register_club {...props} />}
/>
<Route
exact
path="/404"
name="Page 404"
render={(props) => <Page404 {...props} />}
/>
<Route
exact
path="/500"
name="Page 500"
render={(props) => <Page500 {...props} />}
/>
<Route
path="/"
name="Home"
render={(props) => <DefaultLayout {...props} />}
/>
</Switch>
</React.Suspense>
</HashRouter>
</UserContext.Provider>
);
}
export default App;
Thank you for your help!

You are using the HashRouter so the URL you need to aim for is /#/login not /login, but that isn't the biggest problem here.
By using window.location.href you are bypassing the Router entirely and making the browser load the application again from scratch from a new URL.
Assuming you are using React Router version 6 (the current version), the equivalent of window.location.href is the navigate function from the useLocation hook.
However, since you are just creating something to click on that navigates, you should be simply using a <Link> component.
import { Link } from "react-router-dom";
<Link to="/login">
<CIcon icon={cilUser} className="me-2" />
Login
</Link>

Related

Why React does not render component when I redirect to product page

I have an error and can not find any solution in google. The error appears when I want to go to a poduct page and press a button on home page to go to a product page and there I don't have any element rendered, I used React Route to user be able to go to product page and add it to a cart and suppose I did something wrong with providing path but not sure.
VM867:236 Matched leaf route at location "/2" does not have an element. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.
Here is a code for Item Element:
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
function Item() {
const { id } = useParams();
const [item, setItem] = useState([]);
const [loading, setLoading] = useState(false);
console.log("item", item);
// Fetching Data
useEffect(() => {
const fetchedData = async () => {
setLoading(true);
const response = await fetch(`https://fakestoreapi.com/products/${id}`);
const data = response.json();
setItem(data);
};
fetchedData();
}, []);
return (
<div className="container">
{loading ? (
<>
<h3>Loading.....</h3>
</>
) : (
<div className="container">
<p>{item.title}</p>
</div>
)}
</div>
);
}
export default Item;
And for App.js
import { BrowserRouter as Router, Route, Routes } from "react-router-dom";
import ItemsComponent from "./Componets/ItemsComponent";
import Navbar from "./Componets/Navbar";
import Home from "./Componets/Home";
import Item from "./Componets/Item";
import About from "./Componets/About";
import AboutLink from "./Componets/AboutLink";
import Contact from "./Componets/Contact";
import Footer from "./Componets/Footer";
import "./App.css";
function App() {
return (
<>
<Router>
<Navbar />
<Routes>
<Route
exact
path="/"
element={
<>
<Home />
<ItemsComponent />
</>
}
/>
<Route exact path="/:id" component={<Item />} />
<Route exact path="/about" element={<About />} />
</Routes>
<AboutLink />
<Footer />
</Router>
</>
);
}
export default App;
It also affected all styling.
Maybe it's because you have
<Route exact path="/:id" component={<Item />} />
instead of
<Route exact path="/:id" element={<Item />} />
?
I think that instead of this
<Route exact path="/:id" component={<Item />} />
you want either of those
<Route exact path="/:id" component={Item} />
<Route exact path="/:id" element={<Item />} />

Trigger a rerender of parent component when a child component is rendered

I am using the following material-ui theme Paperbase and within the Header.js component, I have the following useEffect hook:
const [temperature, setTemperature] = useState([]);
const getTemperature= async () => {
try {
const response = await fetch('/get-temperature')
const tempData = await response.json();
setTemperature(tempData);
} catch (err) {
console.error(err.message);
}
};
useEffect(() => {
getTemperature();
}, []);
The main purpose of this, is to display the current temperature as info, within the header component, which gets displayed at first page load/render.
Now within my App.js below, I have the following return setup where the above Header component is called.
return (
<Router>
<UserProvider myinfo={myinfo}>
<Switch>
<Route path="/">
<ThemeProvider theme={theme}>
<div className={classes.root}>
<CssBaseline />
<nav className={classes.drawer}>
<Hidden xsDown implementation="css">
<Navigator />
</Hidden>
</nav>
<div className={classes.app}>
<Header
onDrawerToggle={handleDrawerToggle}
/>
<main className={classes.main}>
<Switch>
<Route exact path="/new-user"
render={(props) => <Content key={props.location.key} />}
/>
<Route exact path="/view-results"
render={(props) => <ViewResults key={props.location.key} />}
/>
</Switch>
</main>
</div>
</div>
</ThemeProvider>
</Route>
</Switch>
</UserProvider>
</Router>
);
My question is, how can I trigger a rerender of Header (parent) whenever the user routes to either /new-user or /view-results which in turn calls either Content.js or ViewResults.js, inorder to make the useEffect in Header.js refresh the data, from the REST api fetch and display the latest temperature in the header again?
Ideally anytime Content.js or ViewResults.js is rendered, ensure that Header.js getTemperature() is called.
Any help would be much appreciated.
Your current code is pretty close to a multi layout system. As being a component child of Route, you can access the current location via useLocation() or even the native window.location.pathname.
This is my example of multi layout React app. You can try to use it to adapt to your code.
The MainLayout use a fallback route when no path is specified. It also contains a Header and include a page
const Dispatcher = () => {
const history = useHistory();
history.push('/home');
return null;
};
const App = () => (
<BrowserRouter>
<Switch>
<Route
component={Dispatcher}
exact
path="/"
/>
<Route
exact
path="/login/:path?"
>
<LoginLayout>
<Switch>
<Route
component={LoginPage}
path="/login"
/>
</Switch>
</LoginLayout>
</Route>
<Route>
<MainLayout>
<Switch>
<Route
component={HomePage}
path="/home"
/>
</Switch>
</MainLayout>
</Route>
</Switch>
</BrowserRouter>
);
And here is the code for MainLayout
const MainLayout = ({ children }) => (
<Container
disableGutters
maxWidth={false}
>
<Header location={props.location} />
<Container
component="main"
maxWidth={false}
sx={styles.main}
>
{children}
</Container>
<Footer />
</Container>
);
Now that Header can be anything. You need to put a capture in this component
import { useLocation } from 'react-router-dom'
cont Header = (props) => {
const { pathname } = useLocation();
//alternatively you can access props.location
useEffect(() => {
if (pathname === '/new-user') {
getTemperature();
}
}, [pathname]);
};
Note that Header is not a direct descendant of Route therefore it cannot access the location directly via props. You need to transfer in chain
Route -> MainLayout -> Header
Or better use useLocation

Always redirected to current route instead of desired route

I am using ternary operator to render component using react route. But I am always redirected to "/" route instead of desired component even if the condition is as expected.
I get desired functionality only when I refresh/reload the page.
This is my App.js with all the routes
import React, { useEffect, useState } from 'react';
import Header from './Components/Header';
import Home from './Components/Home';
import Checkout from "./Components/Checkout";
import Payment from "./Components/Payment";
import NewProduct from "./Components/NewProduct";
import OrderSuccess from "./Components/OrderSuccess";
import AddressForm from './Components/AddressForm';
import {BrowserRouter, Switch, Route} from "react-router-dom";
import { Redirect } from 'react-router';
import Login from './Components/Login';
import Orders from "./Components/Orders";
import Account from './Components/Account';
import { connect } from 'react-redux';
const App=()=>{
const user = (JSON.parse(localStorage.getItem("profile")));
const defaultRoutes= ()=>{
return(
<div>
<Header/>
<Switch>
<Route path="/account-settings" exact component={()=>user ? <Account />: <Redirect to="/" />} />
<Route path="/orders" exact component={()=>user ? <Orders /> : <Redirect to="/" />} />
<Route path="/checkout" exact component={()=>user ? <Checkout />: <Redirect to="/" />} />
<Route path="/payment" exact component={()=>user ? <Payment /> : <Redirect to="/" />} />
<Route path="/account-settings/add-new-address" exact component={()=>user?.result ? <AddressForm /> : <Redirect to="/" />} />
<Route path="/" exact component={Home} />
</Switch>
</div>
)
}
return (
<BrowserRouter>
<Switch>
<Route path="/login" exact component={()=>user ? <Redirect to="/" />:<Login />} />
<Route component={defaultRoutes} />
</Switch>
</BrowserRouter>
);
}
export default App;
This is my index.js file
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import { createStore, applyMiddleware, compose } from "redux";
import thunk from "redux-thunk";
import "./index.css"
import reducers from "./reducers/index";
const store = createStore(reducers,{},compose(applyMiddleware(thunk)));
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>
, document.getElementById("root")
)
This is reducer where I am updating my localstorage
export default (state={authData:null},action)=>{
switch(action.type){
case "AUTH":
localStorage.setItem("profile",JSON.stringify({...action?.data}));
return {...state, authData: action.data, loading: false, errors: null};
case "LOGOUT":
localStorage.clear();
return {...state,authData:null};
default:
return "";
}
}
Remove the ternary in the router. Use useHistory to redirect to "/" if the condition is not met.
For checking the condition, create a custom hook called useCheckUser which checks if there is a user in the localStorage.
In every component where user is required,
import useCheckUser from "file-address"
import { useHistory } from "react-router"
const Component = () => {
let history = useHistory();
let user = useCheckUser();
if (!user) {
history.push("/");
}
return ()
}
The useCheckUser hook should be something similar to
const useCheckUser = () => {
let user = localStorage.getItem("profile");
if (user) {
return JSON.parse(user);
}
return null;
};
export default useCheckUser;
NOTE: If your only requirement is rendering components when the user is present, you can change your custom hook so that it does everything including the redirecting. This is just to return the current user. So this can be used if you want to render certain components like auth pages if and only if the user is not present.
try to take the user a State (useState), and set it in the useEffect like this:
const [user, setUser] = useState(null);
useEffect(() => {
setUser(localStorage.getItem("profile"))
}, [])
it will set the "user" as your page rendered
function App() {
const [user, setUser] = useState(null);
useEffect(() => {
setUser(localStorage.getItem("profile"))
}, [])
const authentication = {
getLogInStatus() {
return user;
},
};
}
function SecuredRoute(props) {
return (
<Route
path={props.path}
render={(data) =>
authentication.getLogInStatus() ? (
<props.component
{...data}
></props.component>
) : (
handleRedirect()
)
}
></Route>
);
}
const handleRedirect = () => {
let login = window.confirm(
"please Register or log in to access this page!"
);
if (login) {
return <Redirect path="/"></Redirect>;
}
};
return (
<BrowserRouter>
<Switch>
// those routes which don't needs authetication
<Route path="/home" compponent={Home} />
<Route path="/login" compponent={Login} />
//and others
// those routes which needs authetication
<SecuredRoute path="/bookings" component={Bookings} />
<SecuredRoute
path="/booking-details"
component={BookingDetails}
/>
<SecuredRoute path="/favorites" component={Favorites} />
<SecuredRoute path="/profile" component={Profile} />
</Switch>
</BrowserRouter>
);
}
Issue
You are close. The issue here is that even though you store the auth in localStorage and update the redux state, App isn't being rerendered to "pick up" the new auth value from localStorage.
Solution
Initialize the redux state from localStorage.
Select the authentication state from your Redux store. This is so changes to the store trigger subscribed components to rerender.
Auth Reducer
const initialState={
authData:JSON.parse(localStorage.getItem("profile")),
loading:false,
errors:null
};
export default (state = initialState, action) => {
switch(action.type){
case "AUTH":
localStorage.setItem("profile", JSON.stringify({ ...action?.data }));
return {
...state,
authData: action?.data,
loading: false,
errors: null
};
case "LOGOUT":
localStorage.clear();
return { ...state, authData: null };
default:
return state;
}
};
App
import { useSelector } from "react-redux";
const App = () => {
const user = useSelector(state => state.auth.authData);
const defaultRoutes = () => {
return (
<div>
<Header/>
<Switch>
<Route
path="/account-settings"
render={() => user ? <Account />: <Redirect to="/" />}
/>
<Route
path="/orders"
render={() => user ? <Orders /> : <Redirect to="/" />}
/>
<Route
path="/checkout"
render={() => user ? <Checkout />: <Redirect to="/" />}
/>
<Route
path="/payment"
render={() => user ? <Payment /> : <Redirect to="/" />}
/>
<Route
path="/account-settings/add-new-address"
render={() => user?.result ? <AddressForm /> : <Redirect to="/" />}
/>
<Route path="/" component={Home} />
</Switch>
</div>
)
};
return (
<BrowserRouter>
...
</BrowserRouter>
);
}
Suggestion
Review the auth workflow and create a PrivateRoute component that handles the redirect for you.
Example:
const PrivateRoute = props => {
const user = useSelector(state => state.auth.authData);
return user ? <Route {...props} /> : <Redirect to="/" />
};
Usage:
const App = () => {
const defaultRoutes = () => {
return (
<div>
<Header/>
<Switch>
<PrivateRoute path="/account-settings" component={Account} />
<PrivateRoute path="/orders" component={Orders} />
<PrivateRoute path="/checkout" component={Checkout} />
<PrivateRoute path="/payment" component={Payment} />
<Route
path="/account-settings/add-new-address"
render={() => user?.result ? <AddressForm /> : <Redirect to="/" />}
/>
<Route path="/" component={Home} />
</Switch>
</div>
)
};
return (
<BrowserRouter>
...
</BrowserRouter>
);
}

react router use params returns empty object

I have a web app which is under development which is just like google drive using firebase. I have this useParams() in Dashboard Screen which is the main page of the App with All the different Folder Routes. So for this screen i have used useParams and now when i console.log(params) it shows an empty object {} and also when i click the button it does not navigate only the URL changes
Github Code :- https://github.com/KUSHAD/RDX-Drive/
In App.js
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import PrivateRoute from './Components/Route/PrivateRoute';
import Dashboard from './Screens/Main/Dashboard';
import ViewProfile from './Screens/Profile/ViewProfile';
import Signup from './Screens/Auth/Signup';
import Login from './Screens/Auth/Login';
import ForgotPassword from './Screens/Auth/ForgotPassword';
function App() {
return (
<>
<div className='App'>
<div className='main'>
<BrowserRouter>
<Switch>
{/* Drive */}
<PrivateRoute exact path='/' component={Dashboard} />
<PrivateRoute
exact
path='/folder/:folderId'
component={Dashboard}
/>
{/* Profile */}
<PrivateRoute path='/profile' component={ViewProfile} />
{/* Auth */}
<Route path='/signup' component={Signup} />
<Route path='/login' component={Login} />
<Route path='/forgot-password' component={ForgotPassword} />
</Switch>
</BrowserRouter>
</div>
</div>
</>
);
}
export default App;
In Dashboard.js
import NavBar from '../../Components/Shared/NavBar';
import Container from 'react-bootstrap/Container';
import AddFolderButton from '../../Components/Main/AddFolderButton';
import { useDrive } from '../../services/hooks/useDrive';
import Folder from '../../Components/Main/Folder';
import { useParams } from 'react-router-dom';
export default function Dashboard() {
const params = useParams();
console.log(params);
const { folder, childFolders } = useDrive();
return (
<div>
<NavBar />
<Container fluid>
<AddFolderButton currentFolder={folder} />
{childFolders.length > 0 && (
<div className='d-flex flex-wrap'>
{childFolders.map(childFolder => (
<div
key={childFolder.id}
className='p-2'
style={{ maxWidth: '250px' }}>
<Folder folder={childFolder} />
</div>
))}
</div>
)}
</Container>
</div>
);
}
Issue
After scouring your repo looking for the usual suspect causes for "it does not navigate only the URL changes" I didn't find anything odd like multiple Router components, etc. I think the issue is your PrivateRoute component isn't passing the props to the Route correctly. You're destructuring a prop called rest and then spread that into the Route, but you don't pass a rest prop to the PrivateRoute
export default function PrivateRoute({ component: Component, rest }) { // <-- rest prop
const { currentUser } = useAuth();
return (
<Route
{...rest} // <-- nothing is spread/passed here
render={props => {
return currentUser ? (
<Component {...props} />
) : (
<Redirect to='/login' />
);
}}
/>
);
}
The routes, these are not passed any prop named rest:
<PrivateRoute exact path='/' component={Dashboard} />
<PrivateRoute
exact
path='/folder/:folderId'
component={Dashboard}
/>
What I believe to be occurring here is the exact and path props aren't passed to the underlying Route component and so the first nested component of the Switch is matched and rendered, the "/" one that doesn't have any route params.
Solution
The fix is to spread the rest of the passed props into rest instead of destructuring a named rest prop.
export default function PrivateRoute({ component: Component, ...rest }) {
const { currentUser } = useAuth();
return (
<Route
{...rest}
render={props => {
return currentUser ? (
<Component {...props} />
) : (
<Redirect to='/login' />
);
}}
/>
);
}
An improvement of your private route may be as follows:
export default function PrivateRoute(props) {
const { currentUser } = useAuth();
return currentUser ? (
<Route {...props} />
) : (
<Redirect to='/login' />
);
}
This checks your user authentication and renders either a Route or Redirect. This pattern allows you to use all the regular Route props so you aren't locked into using the render prop to render the component.

Programmatically navigate while using HashRouter

I'm using HashRouter for my routes in a react.js app. I then have a function which does the following:
this.props.history.push('/somePath');
The problem is, ever since I started using HashRouter, the page doesn't push to that path when that function gets called.
I logged this.props.history, and push was there.
How can I programmatically navigate while using HashRouter?
Note: I used withRouter
Here's the code:
import React, { Component } from 'react';
import { HashRouter, Route, Switch, Redirect, withRouter } from 'react-router-dom';
// Other imports
class App extends Component {
navigate = () => {
this.props.history.push('/route1');
console.log(this.props.history);
};
render() {
return (
<div className="App">
<Header />
<HashRouter>
<Switch>
<Route
path="/route1"
exact
render={() => (
<FirstRoute someSetting='setting1'/>
)}
/>
<Route
path="/route2"
exact
render={() => (
<SecondRoute anotherSetting='Really Cool'/>
)}
/>
<Route path="/404" component={NotFound} />
<Route exact path="/" render={() => <HomePage someSettings='Home Page' />} />
<Redirect to="/404" />
</Switch>
</HashRouter>
<BottomBar />
</div>
);
}
}
export default withRouter(App);

Categories

Resources