Closed. This question is not written in English. It is not currently accepting answers.
Stack Overflow is an English-only site. The author must be able to communicate in English to understand and engage with any comments and/or answers their question receives. Don't translate this post for the author; machine translations can be inaccurate, and even human translations can alter the intended meaning of the post.
Closed 6 days ago.
This post was edited and submitted for review 6 days ago.
Improve this question
These two structures make my app work perfectly but there is a react warning where it imitates No routes matched location "/workspace" and I cannot add to <Route path="/workspace" element={<Workspace />} /> the routes because if I do that my app is insanely buggy
export const Workspace = () => {
const location = useLocation();
const isPathOne = location.pathname.startsWith(`/workspace`);
useEffect(() => {
document.body.style.background = isPathOne ? "#1c1f20" : "transparent";
}, [location.pathname, isPathOne]);
return <div className="workspace">{isPathOne ? <Sidebar /> : null}</div>;
};
export default function Switch() {
return (
<>
<Router>
<Workspace />
<Routes>
<Route exact path="/" element={<Home />} />
<Route path="/services" element={<Services />} />
<Route path="/products" element={<Products />} />
<Route path="/authentication/register" element={<RegisterPage />} />
<Route path="/authentication/login" element={<LoginPage />} />
<Route path="/workspace/overview/users" element={<Users />} />
<Route path="/workspace/overview/howitworks" element={<HowItWorks />} />
<Route />
</Routes>
</Router>
</>
);
}
I know that what I'm doing in WorkspaceApp.js is not a good practice since I developed a "way (workaround)" to render my component with the URL without it losing state, which may not make much sense but it does the application have the expected behavior, the bug I mentioned in the title is when clicking on the links available in the sidebar, when you do that, several design bugs occur, such as the state of the sidebar being updated automatically, among others...
I've been at this challenge for a long time and I can't solve it...
Detail, it's no use leaving <Route path="/workspace" element={} /> only in routes and excluding inside Router, I've already tried
Related
This question already has answers here:
What is the alternative for Redirect in react-router-dom v 6.0.0?
(5 answers)
Closed 3 months ago.
I am using react-router where I have following code
<Router basename={config.historyBasename}>
<Routes>
<Route path={routes.landingPage} element={<LandingPage />} />
<Route
path={routes.activateAccount}
element={
!document.referrer.length ? (
redirectTo(appUrls.home)
) : (
<Parent/>
)
}
/>
</Routes>
</Router>
Here, I am using redirectTo which I created custom method. Now here, I am trying to create a custom route which will do
<Route
path={routes.activateAccount}
element={
!document.referrer.length ? (
redirectTo(appUrls.home)
) : (
<Parent/>
)
}
/>
this. How can I create a custom route which will handle this ?
Well you can use Redirect from react-router-dom for Conditionally Redirect to the Default Path
<Route
path={routes.activateAccount}
element={!document.referrer.length ? <Redirect to='/home' /> : <Redirect to='/second-route' />}
/>
For v6 you can use Navigate
<Route
path={routes.activateAccount}
element={
!document.referrer.length ? (
<Navigate replace to='/home' />
) : (
<Navigate replace to='/second-route' />
)
}
/>
Please note however that this won't work when server rendering because the navigation happens in a React.useEffect().
Have a look at Redirects in React Router v6 for some deeper details.
The past couple of years, react-router-dom and react-router introduced the <Redirect /> component which essentially when rendered, redirects the user to a specified location.
For example:
<Route exact path="/">
<Redirect to={"/home"} />
</Route>
redirect the user to /home whenever he arrives on /.
When using react-router-dom#^6.0.0, refrain from using Redirect and use Navigate instead:
<Route
path="/"
element={<Navigate to={"/home"} replace />}
/>
Which essentially serves the same purpose as the code I wrote above.
i have a react app in which i want that if user route start with admin it should have a different navbar
lets take example
normal page
<NormalNavbar/>
<NormalHeader/>
<NormalBody/>
<NormalFooter/>
But if i have the admin route
then i want to have
<AdminNavbar/>
<AdminHeader/>
<AdminBody/>
<AdminFooter/>
The issue is when we wind it inside the Routes then we decide the normal components which are loading i will paste the example below
return (
<div className="App">
<>
<Navbar />
<Routes>
<Route exact path="/" element={<HomePage />} />
<Route exact path="/product/:id" element={<ProductPage />} />
<Route exact path="sarangAdmin/create-product" element={<CreateProduct />} />
<Route exact path="login" element={<Login />} />
<Route exact path="profile" element={<Profile />} />
<Route exact path="register" element={<Register />} />
</Routes>
<Footer />
</>
</div>
);
You can see my current navbar and footer going to be same
you can put elements with conditions like that
{isAdmin? <AdminNavbar> : <NormalNavbar> }
OR
in the navbar component view different menu
See the above answers is good but its not the optimal solution I wanted so I get the solution by looking other git repository here is the repository that shows how you should do it in a perfect way make route component structure and then you can render them conditionally which I wanted in my case the most optimum solution to my question
So I've been working on a project lately using React js (I thought it would be similar to React native), while I pretty much understand most of it as I previously worked with React native a lot. There are still some new things I'm learning for example the react-router-dom npm. So I understand the basics and how it works, but I'm trying to use parameters which change depending on the user (User ID).
The code below shows how I'm currently using my router. While going to home (/) and /user/:id works, I can't go to /user/:id/settings. If I try going to the settings it renders both the /user/:id page and below it renders settings page.
What I want to be able to do is if the user is in the user/:id page they can click a button which takes them to the user/:id/settings instead of the current issue where it renders the setting page below the user page.
App.jsx
export class App extends React.Component {
render() {
return (
<Router>
<Route exact path="/" component={Home} />
<Route path="/user/:id" component={User} />
<Route path="/user/:id/settings" component={Setting} />
</Router>
)
}
};
User.jsx
render() {
return (
<div>
{/* Cool information about the user */}
<div
className="optionContent"
onClick={() => {
let uri = `/user/${this.props.match.params.id}/settings`;
this.props.history.push(uri)
}}
>
Press me
</div>
</div>
);
}
Extra information:
I have tried using variable parameters for users but I wasn't able to full make those work as once the user enters /user/:id page the buttons update the url but not the parameters in this.
I need to have the ID within the url to fetch from the API and some other stuff
Variable url: /user/:id/:type?
This is because with React Router v5 which is currently the latest version as v6 is completed, the routes aren't exact by default which means that for each of the routes, if the current route starts with the route of a component, this component will be displayed.
For your example:
<Router>
<Route exact path="/" component={Home} />
<Route path="/user/:id" component={User} />
<Route path="/user/:id/settings" component={Setting} />
</Router>
If the current route is "/user/user1" then it only matches the User component.
If the current route is "/user/user1/settings/ then it matches User and Settings components so they will both be rendered as you are finding.
To fix it, simply use the exact keyword on the component with the fewer requirements.
<Router>
<Route exact path="/" component={Home} />
<Route exact path="/user/:id" component={User} />
<Route path="/user/:id/settings" component={Setting} />
</Router>
I am building a React app that has a static marketing site and a dynamic app. I am using a combination of React Router and hooks to separate the two and ensure proper routing throughout.
To begin with, I want users who are logged in to be taken directly to the app when they hit the root ("/") and to the static/marketing site when not logged in. The main marketing site home page has a nav bar that allows users to access other routes such as "/about", whereas the app has a separate nav bar for app navigation.
The problem is, while the authentication based routing for the root route seems to be working, and I can navigate to other routes specified in my top-level file, the routes that are included within my static/marketing site are not accessible.
Top-level/index.js
const routing = (
<Provider store={store}>
<Router>
<NavWrapper />
{/* <Switch> */}
<Route exact path="/" component={AuthWrapper} />
<Route path="/signup" component={SignUp} />
<Route path="/login" component={Login} />
{/* </Switch> */}
</Router>
</Provider>
)
ReactDOM.render(routing, document.getElementById('root'));
AuthWrapper.js (here useAuth() is a React hook that evaluates global Redux isAuthenticated state)
const AuthWrapper = (props) => {
return useAuth() ? <App /> : <Website />
}
export default AuthWrapper;
website/index.js
export const Website = () => {
return (
<>
{/* <SiteNav /> */}
<Switch>
<Route exact path="/" component={LandingPage} />
<Route path="/about" component={AboutPage} />
<Route path="/how-it-works" component={HowItWorksPage} />
<Route path="/plans" component={PlansPage} />
<Route path="/press" component={PressPage} />
<Route path="/faq" component={FAQPage} />
<Route path="/legal" component={LegalPage} />
<Route path="/for-dieticians" component={DietitiansPage} />
<Route path="/for-trainers" component={PTsPage} />
</Switch>
</>
)
};
In my app, when I enter localhost:3000/ (unauthenticated) I am correctly taken to my home/landing page. However, if I try to use the navigation (or type in any subroutes) to access "/about" for example, I get a blank screen (other than the nav bar). In the React dev tools, the component isn't even rendering.
I think this is the issue:
<Route exact path="/" component={AuthWrapper} />
You want Authwrapper to be shown for about as well, right? But the above only matches "/" exactly.
You should enable the switch statement, but move the AuthWrapper Route to the bottom and then let it have this path: "/:rest*" (maybe "/*" works too, haven't used react-router in a while).
That way, it will use the Route if the first 2 don't match.
In a React SPA, I have a collection of "pages" under the /src/pages/ folder.
The entry point page is an index.js file under the /src/ folder, where I define a router const like this:
const routing = (
<Router>
<div>
<Switch>
<Route path="/signIn" component={SignIn} />
<Route exact path="/" component={Homepage} />
<Route path="/page1" component={Page1} />
<Route path="/page2" component={Page2} />
<Route path="/page3" component={Page3} />
<Route component={NotFound} />
</Switch>
</div>
</Router>
It works great and all. All pages are navigable like "https://mysuperapp.com/page2" and it will render the Page2 React component.
Concerns arise when I incorporate user session management (log in, log out). If a user is not logged in the app, all pages should automatically redirect to the /signIn page. And viceversa, if a user is already logged, if the /signIn page is accessed, it should automatically redirect to the root homepage.
Right now I have implemented this by adding the following code to all the pages, right after the render() method is declared in the component, like this:
class Page2 extends React.Component {
render() {
if (UserProfile.getUserSessionStatus() !== "logged") {
this.props.history.push("/signIn");
}
}
return (
JSX code to be rendered here...
...
This works, but it feels like a cheap workaround used by someone who is just learning React, not by a professional.
For a proof of concept it works, but I would never dare to use such a thing in a production environment.
So, what's the right, best-practices-aligned way to accomplish this?
One possible approach is to create a Higher Order component(HOC) and use it for protecting any routes that require login.
const PrivateRoute = ({ component: Component, ...rest }) => (
<Route {...rest} render={(props) => (
UserProfile.getUserSessionStatus() === "logged"
? <Component {...props} />
: <Redirect to='/login' />
)} />
)
And then use like this
.....
<PrivateRoute path='/page1' component={Page1} />
.......
Hope this helps!