Why is it not reading the params? - javascript

I am trying to read the code but its returning undefined.
I want to read the code from the route and display it in h3 tag.
The Routing
<Router>
<Routes>
<Route path="/" element={<p>Homepage</p>} />
<Route path="/join" element={JoinRoomPage()} />
<Route path="/create" element={CreateRoomPage()} />
This is the roomCode i want to read in the Room Component
<Route path="/room/:roomCode" element={Room()} />
</Routes>
</Router>
The Room Component
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
export default function Room(props) {
const [room, setRoom] = useState({
votesToSkip: 2,
guestCanPause: true,
isHost: false,
});
let { roomCode } = useParams();
return (
<div>
<h3>{roomCode}</h3>
<p>Votes: {room.votesToSkip}</p>
<p>Guest Can Pause: {room.guestCanPause}</p>
<p>Host: {room.isHost}</p>
</div>
);
}
Thanks in advance

The route components should be passed as JSX, not as an invoked function.
<Router>
<Routes>
<Route path="/" element={<p>Homepage</p>} />
<Route path="/join" element={<JoinRoomPage />} />
<Route path="/create" element={<CreateRoomPage />} />
<Route path="/room/:roomCode" element={<Room />} />
</Routes>
</Router>

Router
<Router>
<Routes>
<Route path="/" element={<p>Homepage</p>} />
<Route path="/join" element={JoinRoomPage()} />
<Route path="/create" element={CreateRoomPage()} />
This is the roomCode i want to read in the Room Component
<Route path="/room/:roomCode" element={<Room />} />
</Routes>
</Router>
Room Component
import { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
const Room = (props) => {
let { roomCode } = useParams();
const [room, setRoom] = useState({
votesToSkip: 2,
guestCanPause: true,
isHost: false,
});
return (
<div>
<h3>{roomCode}</h3>
<p>Votes: {room.votesToSkip}</p>
<p>Guest Can Pause: {room.guestCanPause}</p>
<p>Host: {room.isHost}</p>
</div>
);
}
export default Room;

Related

Blank display when I use link Routes in React

If I search "http://localhost:3000/" or "http://localhost:3000/login", my display is completely blank.
app.js
import React from 'react'
import Login from './pages/login'
import Home from './pages/home'
import Error from './pages/error'
import { Link, Router, Route, Routes } from 'react-router-dom';
function App() {
return (
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="*" element={<Error />} />
</Routes>
)
}
export default App;
home.js
import React from "react";
const Home = () => {
return <h1>The Home</h1>;
};
export default Home;
Refactor to look like:
import { Route, Routes, BrowserRouter } from 'react-router-dom';
// ...
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/login" element={<Login />} />
<Route path="*" element={<Error />} />
</Routes>
</BrowserRouter>
);
};

PrivateRoute in React-router-dom v6 isnt working

I'm trying to use ProtectedRoute as
I can't see why the code isn't working, I'm not getting any error, but at /account it should display <Profile/> and it's blank, I can see the header and footer, but the whole <Profile/> is missing
before trying to use a PrivateRoute, I could display Profile with any problem.
my ProtectedRoute.js
import React from "react";
import { useSelector } from "react-redux";
import { Navigate, Outlet } from "react-router-dom";
const ProtectedRoute = () => {
const {isAuthenticated} = useSelector((state)=>state.user)
return isAuthenticated ? <Outlet /> : <Navigate to="/login"/>
}
export default ProtectedRoute;
my app.js
function App() {
const {isAuthenticated, user} = useSelector(state=>state.user)
React.useEffect(() => {
WebFont.load({
google:{
families: [ "Droid Sans", "Chilanka"],
},
});
store.dispatch(loadUser())
}, []);
return (
<Router>
<Header/>
{isAuthenticated && <UserOptions user={user} />}
<Routes>
<Route exact path="/" element={<Home/>}/>
<Route exact path="/product/:id" element={<ProductDetails/>}/>
<Route exact path="/products" element={<Products/>}/>
<Route path="/products/:keyword" element={<Products/>}/>
<Route exact path="/search" element={<Search/>}/>
<Route exact path="/account" element={<ProtectedRoute/>}/>
<Route exact path="/account" element={<Profile/>}/>
<Route exact path="/login" element={<LoginSignUp/>}/>
</Routes>
<Footer/>
</Router>
);
}
export default App;
and my Profile
const Profile = () => {
const { user, loading, isAuthenticated} = useSelector((state) => state.user);
const navigate = useNavigate();
useEffect(() => {
if(isAuthenticated === false){
navigate("/login");
}
}, [navigate,isAuthenticated])
return (
<Fragment>
<MetaData title={`${user.name}'s Profile`} />
<div className="profileContainer">
<div>
<h1>My Profile</h1>
<img src={user.avatar?.url} alt={user.name} />
<Link to="/me/update">Edit Profile</Link>
</div>
<div>
<div>
<h4>Full Name</h4>
<p>{user.name}</p>
</div>
<div>
<h4>Email</h4>
<p>{user.email}</p>
</div>
<div>
<h4>Joined On</h4>
<p>{String(user.createdAt).substr(0, 10)}</p>
</div>
<div>
<Link to="/orders">My Orders</Link>
<Link to="/password/update">Change Password</Link>
</div>
</div>
</div>
</Fragment>
);
};
export default Profile;
You are rendering two routes for the same "/account" path. ProtectedRoute is rendered on its own self-closing route, so the second route rendering Profile is unreachable.
<Routes>
<Route exact path="/" element={<Home/>}/>
<Route exact path="/product/:id" element={<ProductDetails/>}/>
<Route exact path="/products" element={<Products/>}/>
<Route path="/products/:keyword" element={<Products/>}/>
<Route exact path="/search" element={<Search/>}/>
<Route exact path="/account" element={<ProtectedRoute/>}/>
<Route exact path="/account" element={<Profile/>}/> // <-- unreachable, oops!
<Route exact path="/login" element={<LoginSignUp/>}/>
</Routes>
Remove the path prop from the layout route rendering the ProtectedRoute and ensure it is actually wrapping other Route components. You may as well also remove the exact prop on all the routes as this prop was removed in RRDv6.
Example:
<Router>
<Header/>
{isAuthenticated && <UserOptions user={user} />}
<Routes>
<Route path="/" element={<Home />} />
<Route path="/product/:id" element={<ProductDetails />} />
<Route path="/products" element={<Products />} />
<Route path="/products/:keyword" element={<Products />} />
<Route path="/search" element={<Search />} />
<Route element={<ProtectedRoute />}>
<Route path="/account" element={<Profile />} /> // <-- wrapped by layout route!
</Route>
<Route path="/login" element={<LoginSignUp />} />
</Routes>
<Footer/>
</Router>
The ProtectedRoute component doesn't appear to wait for the user state to populate before rendering either the Outlet for protected content or the redirect. Apply some conditional rendering to render a loading indicator or similar while the user state is populated.
import React from "react";
import { useSelector } from "react-redux";
import { Navigate, Outlet } from "react-router-dom";
const ProtectedRoute = () => {
const user = useSelector((state) => state.user);
if (!user) return null; // <-- or loading indicator, etc...
return user.isAuthenticated
? <Outlet />
: <Navigate to="/login" replace />;
}
export default ProtectedRoute;

useEffect() is not able to load data for the second time as soon as the page loaded manually

this is app.js
import Header from './components/Header/Header';
import Login from './components/Login/Login';
import { BrowserRouter as Router, Route,Routes } from "react-router-dom";
import Register from './components/Register/Register';
import About from './components/About/About';
import Update from './components/Update/Update';
import Contact from './components/Contact/Contact';
import Home from './components/Home/Home';
import Logout from './components/Logout/Logout';
import Project from './components/Project/Project';
import Error from './components/Error';
import { useDispatch,useSelector } from 'react-redux';
import { useEffect } from 'react';
import { loadUser } from './actions/userActions';
function App() {
const dispatch = useDispatch();
const {loading, user} = useSelector((state) => state.user);
useEffect(() => {
dispatch(loadUser());
}, [dispatch]);
return (
<div className="App">
<Router>
<Header />
<Routes>
<Route exact path="/" element={<Home
userhome = {user} />} />
<Route exact path="/login" element={<Login />} />
<Route exact path="/signup" element={<Register />} />
<Route exact path="/about" element={<About /> } />
<Route exact path="/update" element={<Update /> } />
<Route exact path="/contact" element={<Contact /> } />
<Route exact path="/logout" element={<Logout /> } />
<Route exact path="/project" element={<Project /> } />
<Route exact path="/profile" element={<About /> } />
<Route path="*" element={<Error />} />
</Routes>
</Router>
</div>
);
}
export default App;
this is home.js
in any react app, "localhost:3000" will automatically get rendered (if there is no error).
In my case also same thing is happening, when the react app loads for the first time, it does not give any error.
The output for first time is Name : Prajwal Raj
But as soon as i load the same home route for second time is gives error ,
Cannot read properties of undefined (reading 'name')
const Home = ({userhome}) =>{
return (
<div className="home">
<h1>HOME</h1>
<p>Name : {userhome.name}</p>
</div>
);
};
export default Home;

Parameters Routing

I'm having a problem in getting the output of the "match" object value in this parameter routing code.
This is class where I use match:
import React from "react";
const ProductDetails = (props) => {
console.log(props.match);
return <h1>Details No. </h1>;
};
export default ProductDetails;
And the code I use for using the route is:
import React, { Component } from "react";
import NavBar from "./navbar";
import ProductDetails from "./productDetails";
class App extends Component {
render() {
return (
<React.Fragment>
<NavBar
productsCount={this.state.Product.filter((p) => p.count > 0).length}
/>
<main className="container">
<Routes>
<Route path="/about" element={<About />} />
<Route path="/" element={<Home />} />
<Route path="/contact" element={<Contact />} />
<Route
path="/cart"
element={
<ShoppingCart
products={this.state.Product}
onReset={this.resetData}
onIncrement={this.incrementEntry}
onDelete={this.deleteEntery}
/>
}
/>
<Route path="/products/:id" element={<ProductDetails />} />
</Routes>
</main>
</React.Fragment>
);
}
}
And I get the answer as "undefined" and a lot of red errors msgs.
if you are using react router v6 and what you want to do is getting the id, it would be:
import React from "react";
const ProductDetails = () => {
const {id} = useParams();
return <h1>Details No. {id}</h1>;
};
export default ProductDetails;
or if you really want the match object:
import React from "react";
const ProductDetails = () => {
const match = useMatch();
return <h1>Details No.</h1>;
};
export default ProductDetails;
What is element? If you use react-router-dom for routing you must set the component for any route.
<BrowserRouter>
<Route path ="/about" component= {<About />} />
<Route path ="/" component= {<Home/>}/>
<Route path ="/contact" component= {<Contact/>}/>
<Route path ="/cart" component= {<ShoppingCart
products= {this.state.Product}
onReset ={this.resetData}
onIncrement ={this.incrementEntry}
onDelete = {this.deleteEntery}/>}/>
<Route path="/products/:id" component={<ProductDetails />}/>
</BrowserRouter>

How can I split React Router into multiple files

My routes file is getting rather messy so I decided to split them out into separate files.
My problem is that if I used 2 separate files, whichever comes after the first include does not get rendered:
const routes = (
<div>
<Switch>
<Route exact path="/" component={Home} />
{Registration} //Does get rendered
//Everything below this does not get a route
{Faq}
<Route path="/login" component={login} />
<Route component={NoMatch} />
</Switch>
</div>
);
If I switch Faq with registration then all the Faq routes will work.
RegistrationRoutes.js
import Introduction from '../containers/Registration/Introduction';
import Login from '../containers/Login';
const Routes = (
<Switch>
<Route path="/login" component={Login} key="login" />,
<Route path="/registration/introduction" component={Introduction} key="registration-intro" />
</Switch>
);
export default Routes;
FaqRoutes.js
import Faq from '../containers/Faq';
import faqJson from '../json_content/faq/faq';
import FaqCategory from '../containers/Faq/faqCategory';
const Routes = (
<Switch>
<Route path="/faq/:category" component={FaqCategory} key="faqCat" />
<Route path="/faq" render={props => <Faq data={faqJson} />} key="faq" />
</Switch>
);
export default Routes;
May be you can move them to config file and load them from there.
App.tsx
import routes from "./routes";
const App: React.FC = () => {
return (
<BrowserRouter>
<div>
<Switch>
{routes.data.map((entry) => {return (<Route {...entry}/>)})}
</Switch>
</div>
</BrowserRouter>
);
};
export default App;
router.ts
const routes = {data: [
{
key: "one",
path: "/three"
},
{
key: "two",
path: "/two"
}
]
}
export default routes;
This will keep your code simple
Your code would get translated to something like this,
const routes = (
<div>
<Switch>
<Route exact path="/" component={Home} />
<Switch>
<Route path="/login" component={Login} key="login" />,
<Route path="/registration/introduction"
component={Introduction} key="registration-intro" />
</Switch>
//Everything below this does not get a route
{Faq}
<Route path="/login" component={login} />
<Route component={NoMatch} />
</Switch>
</div>
);
This is wrong way to implement routing with react-router-dom or React-Router v4.
For Correct way of implementation You can see this example.
index.js
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter, Switch, Route, Link } from "react-router-dom";
import LandingPage from "../Registration";
const Home = () => {
return <div>
Home Component
<Link to="/auth/login">Login</Link>
</div>;
};
function App() {
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Start editing to see some magic happen!</h2>
<BrowserRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/auth" component={LandingPage} />
</Switch>
</BrowserRouter>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Registration.js
import React, { Component } from 'react';
import { Switch, Route, Link, Redirect } from 'react-router-dom';
const LoginRegister = (props) => {
return (
<div>
Login or register
<Link to="/login">Login</Link>
<br />
<Link to="/signup" >Signup</Link>
</div>
);
}
const Login = (props) =>{
console.log("login ", props);
return (
<div>
Login Component
<Link to="/auth/signup" >Signup</Link>
</div>
);
}
const Signup = () => (
<div>
Signup component
<Link to="/auth/login" >Login</Link>
</div>
);
class LandingPage extends Component {
render() {
console.log('Landing page',this.props);
const loginPath = this.props.match.path +'/login';
const signupPath = this.props.match.path + '/signup';
console.log(loginPath);
return (
<div className="container" >
Landing page
<Switch>
<Route path={loginPath} component={Login} />
<Route path={signupPath} component={Signup} />
<Route path="/" exact component={LoginRegister} />
</Switch>
</div>
);
}
}
export default LandingPage;
Try the following
RegistrationRoutes.js
import Introduction from '../containers/Registration/Introduction';
import Login from '../containers/Login';
const Routes = (
<React.Fragment>
<Route path="/login" component={Login} key="login" />,
<Route path="/registration/introduction" component={Introduction} key="registration-intro" />
</React.Fragment>
);
export default Routes;

Categories

Resources