Props not pass in the route though pass it in the render - javascript

I am trying to pass the props in the route component, I know we cannot directly pass to that, so I used to render, but the props are still undefined in the child component.
import React from 'react';
//components
import Register from '../components/register/register';
import Login from "../components/login/login";
import ForgetPassword from '../components/forget-password/forget-password';
//redux
import {store} from "../redux/store";
import { connect } from 'react-redux';
import actions from "../redux/authentication/actions";
//react-router
import {BrowserRouter,Route,Switch} from "react-router-dom";
//antd
import "antd/dist/antd.css";
//css
import '../global/_global.scss';
function Authentication(props) {
console.log("PROPS", props)
return (
<div className="App">
<BrowserRouter>
{/*switch-component will render first that matches the includes path*/}
<Switch>
<Route path='/login' component={Login} />
<Route exact path='/' component={Login} />
<Route path='/register'
render={(props) => (
<Register {...props} check={props.registerUser} />
)}
/>
<Route path='/forget-password' component={ForgetPassword} />
</Switch>
</BrowserRouter>
</div>
);
}
function mapStateToProps(state){
return state.reducers;
}
export default connect(mapStateToProps, actions)(Authentication);

try using like this
return (
<Route
render={routeProps => (
<Component {...routeProps} />
)}
/>
);
instead of
return (
<Route
render={(routeProps) => (
<Component {...routeProps} />
)}
/>
);

Related

React router is showing No Router matched

App.js
import Login from './Auth/components/login/Login';
import { Route, BrowserRouter, Routes, Outlet } from 'react-router-dom';
import SignIn from './Auth/components/signin/Signin';
import Home from './Home/Home';
import Dogs from './pets/Dogs';
import Cats from './pets/Cats';
import Others from './pets/Others';
import Pets from './pets/Pets';
import { Header } from './ui/Header/Header';
import { ContextClickValue } from './context/ContextClick';
import Cart from './Auth/components/cart/Cart';
function App() {
return (
<>
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} >
</Route>
</Routes>
<Header />
<Routes>
<Route path="/login" element={<Login />}></Route>
<Route path="/signin" element={<SignIn />}></Route>
<Route path="/cart" element={<Cart />}></Route>
<Route path="pets" element={< Outlet />}>
<Route index element={<Pets />} />
<Route path="dogs" element={<Dogs />} />
<Route path="cats" element={<Cats />} />
<Route path="others" element={<Others />} />
</Route>
</Routes>
</BrowserRouter>
</>
);
}
export default App;
Header.js
import { menuItems } from "../../Home/MenuItems";
import MenuItemComponent from "./MenuItemComponent";
import HeaderStyles from "./Header.module.css";
import { ContextClick, ContextClickValue } from "../../context/ContextClick";
import AddShoppingCartIcon from '#mui/icons-material/AddShoppingCart';
import {useSelector} from 'react-redux'
import { NavLink, useNavigate } from "react-router-dom";
export function Header() {
const cart = useSelector(state => state.cart.cart)
const navigate = useNavigate()
function navigateToCart(e){
e.preventDefault()
navigate('/cart')
}
let total = 0;
return (
<section className={HeaderStyles.navbar}>
<header>
<h4 className={HeaderStyles.logo}>PETSHOP</h4>
<nav>
<MenuItemComponent items={menuItems} />
</nav>
</header>
<section style={{ float:'right',margin:30, color:'white'}}>
<AddShoppingCartIcon style={{cursor:'pointer'}} onClick={navigateToCart}/>
{cart.forEach(item => {
total += item.quantity
})}
<span>{total}</span>
</section>
</section>
)
}
i have tried using Navlink also
<NavLink to="/cart">
<AddShoppingCartIcon style={{cursor:'pointer'}} />
{cart.forEach(item => {
total += item.quantity
})}
</NavLink>
I am trying to to navigate to cart (i don't know why it is not working)
In dev Tools it is showing to matching Router (i tried clearing cache and hard reload and restarted my server)
I have replaced cart to login for checking it is Navigation Successfully
sandBox link
https://codesandbox.io/p/github/muthyalaDivyaVenkatesh/authentication/master
Can Anyone let me know Why it is Not Working .
Issues
You are rendering 2 Header components, one inside the Home component within a Routes component, and another outside the routes on it's own. The Header renders links, one of which targets "/cart", but the Routes component isn't rendering a route for that path. The other Routes component is missing a route rendering on path "/".
Additionally, the Cart component isn't returning mapped JSX for the cart data selected from state.
function Cart() {
const cart = useSelector((state)=> state.cart.cart)
return (
<div>
{cart.map(cartItem => {
<ShoppingCard // <-- not returned!!
imageUrl={cartItem.imageUrl}
price={cartItem.price}
/>
})}
</div>
)
}
Solution
Create a layout component that renders the Header component, and remove the Header from the Home component.
App.js
const AppLayout = () => (
<>
<Header />
<Outlet />
</>
);
function App() {
return (
<>
<BrowserRouter>
<Routes>
<Route element={<AppLayout />}>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="/signin" element={<SignIn />} />
<Route path="/cart" element={<Cart />} />
<Route path="pets">
<Route index element={<Pets />} />
<Route path="dogs" element={<Dogs />} />
<Route path="cats" element={<Cats />} />
<Route path="others" element={<Others />} />
</Route>
</Route>
</Routes>
</BrowserRouter>
</>
);
}
Home.js
export default function Home() {
return (
<>
<ImageChanging />
<TopDeals />
</>
);
}
Cart.js
function Cart() {
const cart = useSelector((state) => state.cart.cart);
return (
<div>
<h1>Cart</h1>
{cart.map((cartItem) => {
return ( // <-- return the ShoppingCard component
<ShoppingCard
width={300}
height={300}
{...cartItem}
/>
);
})}
</div>
);
}

Why unable to use protectRoute inside Router in react?

I have a react application in which users can access the homepage only after login/signup.
I have used protectRoutes to implement this , however I m getting the following error inside Router component:
A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.
The code for app.js file:
import {useState} from 'react'
import './App.css';
import {Routes,Route,Link} from 'react-router-dom'
import SignupPage from './Pages/SignupPage';
import LoginPage from './Pages/LoginPage';
import Homepage from './Pages/Homepage';
import PrivateRoute from "./Pages/PrivateRoute";
import {HashRouter as Router} from 'react-router-dom'
function App() {
const [username,setUsername]=useState("");
const [currentUser,setCurrentUser]=useState({});
return (
<Router>
<div className="App">
<Route path="/" exact element={<SignupPage></SignupPage>}/>
<Route path="/signup" exact element={<SignupPage currentuser={currentUser} setcurrentuser={setCurrentUser} setusername={setUsername}></SignupPage>}/>
<Route path="/login" exact element={<LoginPage></LoginPage>}/>
<PrivateRoute path="/homepage" exact currentuser={currentUser} element={<Homepage user={currentUser} username={username} setusername={setUsername}></Homepage>}/>
</div>
</Router>
);
}
export default App;
Whats the error here and how do I fix it?
Issue
You are rendering Route components directly and are not wrapping them in a Routes component.
Solution
Refactor the PrivateRoute component to render an Outlet component instead of a Route and wrap the routes you want to protect.
Example:
import { Navigate, Outlet } from 'react-router-dom';
const PrivateRoute = ({ currentuser }) => {
// auth business logic
return isAuthenticated
? <Outlet />
: <Navigate to="/login" replace />;
};
...
import { HashRouter as Router, Routes, Route, Link} from 'react-router-dom'
function App() {
const [username,setUsername]=useState("");
const [currentUser,setCurrentUser]=useState({});
return (
<Router>
<div className="App">
<Routes>
... unprotected routes ...
<Route path="/" element={<SignupPage />} />
<Route
path="/signup"
element={(
<SignupPage
currentuser={currentUser}
setcurrentuser={setCurrentUser}
setusername={setUsername}
/>
)}
/>
<Route path="/login" element={<LoginPage />} />
...
<Route element={<PrivateRoute currentuser={currentUser} />}>
... protected routes ...
<Route
path="/homepage"
element={(
<Homepage
user={currentUser}
username={username}
setusername={setUsername}
/>
)}
/>
...
</Route>
</Routes>
</div>
</Router>
);
}

why Passing Props in Private Route in ReactJs not working properly

Here is mycode of the file PrivateRoute.js
import React from "react";
import {Route,Redirect} from "react-router-dom"
import {isAuthenticated} from "./index"
const PrivateRoutes = (props)=>{
return(
isAuthenticated()?(<Route
render={ (props) =>
<component {...props}/>} />):
(<Redirect to={{ pathname:"/signin"}}/>)
// <h1>hey there</h1>
)
}
export default PrivateRoutes;
In this code it is saying that value of props is read but never used but iam using it in render function,destructuring is also not working here.
Here isAuthenticated() is my boolean function . If it evaluates to true i want to get on more route to user dashboard.
This is how my routes.js file looks like
import React from 'react'
import {BrowserRouter,Route,Switch} from "react-router-dom";
import AdminRoutes from './auth/helper/AdminRoutes';
import PrivateRoutes from './auth/helper/PrivateRoutes';
import Home from './core/Home';
import AdminDashboard from './user/AdminDashBoard';
import Signin from './user/Signin';
import Signup from './user/Signup';
import UserDashboard from './user/UserDashBoard';
function Routes() {
return (
<BrowserRouter>
<Switch>
<Route exact path='/' component={Home} />
<Route exact path="/signup" component={Signup} />
<Route exact path="/signin" component={Signin} />
<PrivateRoutes component="UserDashboard" exact path="/user/dashboard"/>
<AdminRoutes exact path="/admin/dashboard" component={AdminDashboard}/>
</Switch>
</BrowserRouter>
)
}
export default Routes
Help me to solve this problem.
This is because you have declared *two functions, each taking a props object argument, but only the inner/nested function's props is referenced.
Rename the nested props to something else like routeProps and spread both to the rendered component. Remember also that valid React component names are PascalCased.
Example:
const PrivateRoutes = ({ component: Component, ...props }) => {
return isAuthenticated()
? (
<Route
render={(routeProps) => (
<Component {...props} {...routeProps} />
)}
/>
) : <Redirect to={{ pathname:"/signin"}}/>;
}
Then also fix the PrivateRoutes component use to pass a value React component reference instead of a string.
<Switch>
<Route path="/signup" component={Signup} />
<Route path="/signin" component={Signin} />
<PrivateRoutes component={UserDashboard} path="/user/dashboard" />
<AdminRoutes path="/admin/dashboard" component={AdminDashboard} />
<Route path='/' component={Home} />
</Switch>

React router rendering two child components instead of just one

I'm trying to add routes to my application but for some reason there are two components being rendered to the page instead of just one.
My code looks like this (the relevant part):
import React from "react";
import Board from "./Components/Board";
import Navbar from "./Components/Navbar";
import TaskDetail from "./Components/TaskDetail";
import { LanesProvider } from "./Context/lanes.context";
import { TasksProvider } from "./Context/tasks.context";
import { BrowserRouter, Route, Switch } from "react-router-dom";
function App(props) {
const getTask = props => {
return <TaskDetail />;
};
return (
<>
<LanesProvider>
<TasksProvider>
<Navbar />
<Board />
<BrowserRouter>
<Switch>
<Route exact path="/" render={() => <Board />} />
<Route exact path="/board" render={() => <Board />} />
<Route exact path="/board/:taskName" render={() => getTask()} />
</Switch>
</BrowserRouter>
</TasksProvider>
</LanesProvider>
</>
);
}
Now basically when I'm navigating to "localhost/board/test" I would expect to just see the <TaskDetail/> component but instead I get the <Board /> AND <TaskDetail/>.
I didn't expect this to happen because of the exact boolean.
FYI: getTask() is only returning a component right now because I wanted to get the routes to work first before implementing further logic.
So far I could not find a solution to this.
Thank you in advance.
There is a <Board /> component outside your <BrowserRouter>
import React from "react";
import Board from "./Components/Board";
import Navbar from "./Components/Navbar";
import TaskDetail from "./Components/TaskDetail";
import { LanesProvider } from "./Context/lanes.context";
import { TasksProvider } from "./Context/tasks.context";
import { BrowserRouter, Route, Switch } from "react-router-dom";
function App(props) {
const getTask = props => {
return <TaskDetail />;
};
return (
<>
<LanesProvider>
<TasksProvider>
<Navbar />
<Board /> --> Remove this component from here
<BrowserRouter>
<Switch>
<Route exact path="/" render={() => <Board />} />
<Route exact path="/board" render={() => <Board />} />
<Route exact path="/board/:taskName" render={() => getTask()} />
</Switch>
</BrowserRouter>
</TasksProvider>
</LanesProvider>
</>
);
}

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