I already searched a lot and could not find an answer. In my SolidJs app, the second route is not redered in root element:
import { Routes, Route, useLocation } from "solid-app-router"
import { useNavigate } from 'solid-app-router';
const Login = lazy(() => import("./pages/login"));
const Operation = lazy(() => import("./pages/operation"));
export default function App() {
const navigate = useNavigate();
const location = useLocation();
onMount(() => {
const token = localStorage.getItem('token');
if (!token && location.pathname !== '/') {
navigate("/", { replace: true });
}
if (token && location.pathname === '/') {
navigate("/operations", { replace: true });
}
});
return (
<Routes>
<Route path='/' component={Login} />
<Route path='/operations' component={Operation} />
</Routes>
)
}
Everything looks OK at component Operation and if I call this component in first route like bellow it work:
<Route path='/' component={Operation} />
The root component should be wrapped in Router component.
I struggled with this for a while and realised that the application needs to make reference to the Routes by means of an <A> tag.
If you look at this part of the docs, it mentions that these tags include an active class which seems to be used to tell the application to actually bundle this component on build time otherwise by default it is not included.
So if you put Operations somewhere in your homepage like a Navbar, that page/component should bundle in on deployment.
By default though all routes in Routes in dev environment should work so if it is not working in dev environment I would just check that the module is being resolved correctly.
Related
My react app is inside a java struts project, which includes a header. There is a certain element in that header that changes depending on certain routes being hit.
For this it would be much simpler to listen to when a route changes where my Routes are defined. As opposed to doing it in every route.
Here is my
App.js
import {
BrowserRouter as Router,
Route,
useHistory,
useLocation,
Link
} from "react-router-dom";
const Nav = () => {
return (
<div>
<Link to="/">Page 1 </Link>
<Link to="/2">Page 2 </Link>
<Link to="/3">Page 3 </Link>
</div>
);
};
export default function App() {
const h = useHistory();
const l = useLocation();
const { listen } = useHistory();
useEffect(() => {
console.log("location change");
}, [l]);
useEffect(() => {
console.log("history change");
}, [h]);
h.listen(() => {
console.log("history listen");
});
listen((location) => {
console.log("listen change");
});
return (
<Router>
<Route path={"/"} component={Nav} />
<Route path={"/"} component={PageOne} exact />
<Route path={"/2"} component={PageTwo} exact />
<Route path={"/3"} component={PageThree} exact />
</Router>
);
}
None of the console logs get hit when clicking on the links in the Nav component. Is there a way around this?
I have a CodeSandbox to test this issue.
Keep in mind that react-router-dom passes the navigation object down the React tree.
You're trying to access history and location in your App component, but there's nothing "above" your App component to provide it a history or location.
If you instead put your useLocation and useHistory inside of PageOne/PageTwo/PageThree components, it works as intended.
Updated your codesandbox:
https://codesandbox.io/s/loving-lamarr-bzspg?fontsize=14&hidenavigation=1&theme=dark
I have a website made with Docusaurus v2 that currently contains documentation. However, I would like to add a page of a list of workflows where if a workflow in the list is clicked, the user would be shown a page of additional details of that workflow. For now it seems docusaurus.config seems to be handling most of the routing, but is there a way I can add a dynamic route like /workflows/:id? I made a separate standalone app which had a Router object and it worked if my App.js looks like this:
// App.js
import Navigation from './Navigation'
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';
function App() {
return (
<Router>
<Navigation />
<Switch>
<Route path="/" exact component={Home}></Route>
<Route path="/workflows" exact component={Workflows}></Route>
<Route path="/workflows/:id" component={WorkflowItem}></Route>
</Switch>
</Router>
)
}
Is it possible to add the Router somewhere in Docusaurus?
Thanks!
I solved this by creating a simple plugin to add my own custom routes. Documentation here.
Let's call the plugin plugin-dynamic-routes.
// {SITE_ROOT_DIR}/plugin-dynamic-routes/index.js
module.exports = function (context, options) {
return {
name: 'plugin-dynamic-routes',
async contentLoaded({ content, actions }) {
const { routes } = options
const { addRoute } = actions
routes.map(route => addRoute(route))
}
}
}
// docusaurus.config.js
const path = require('path')
module.exports = {
// ...
plugins: [
[
path.resolve(__dirname, 'plugin-dynamic-routes'),
{ // this is the options object passed to the plugin
routes: [
{ // using Route schema from react-router
path: '/workflows',
exact: false, // this is needed for sub-routes to match!
component: '#site/path/to/component/App'
}
]
}
],
],
}
You may be able to use the above method to configure sub-routes as well but I haven't tried it. For the custom page, all you need is the Switch component (you are technically using nested routes at this point). The Layout component is there to integrate the page into the rest of the Docusaurus site.
// App.js
import React from 'react'
import Layout from '#theme/Layout'
import { Switch, Route, useRouteMatch } from '#docusaurus/router'
function App() {
let match = useRouteMatch()
return (
<Layout title="Page Title">
<Switch>
<Route path={`${match.path}/:id`} component={WorkflowItem} />
<Route path={match.path} component={Workflows} />
</Switch>
</Layout>
)
}
I have followed this tutorial to implement authentication in my gatsby project. The problem is I have first setup the project and the routing is made from the pages folder and then I have implemented the above auth code but it still taking the routes from the pages folder and not from the app.js file. Could someone please help how can I route my components from the app.js instead of using from pages folder.
This is my gatsby-nodejs file
// Implement the Gatsby API “onCreatePage”. This is
// called after every page is created.
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
// page.matchPath is a special key that's used for matching pages
// only on the client.
if (page.path.match(/^\/app/)) {
page.matchPath = "/app/*"
// Update the page.
createPage(page)
}
}
here is src/pages.app.js
import React from "react"
import { Router } from "#reach/router"
import Layout from "../components/layout"
import Home from '../components/dashboard/home/container'
import Login from '../components/marketing/home/pulsemetrics'
import { isLoggedIn } from "../services/auth"
console.log('vvvvvvvvvvvvvvvvvvvvv')
const PrivateRoute = ({ component: Component, location, ...rest }) => {
console.log('hjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiii')
if (!isLoggedIn() && location.pathname !== `/app/login`) {
// If the user is not logged in, redirect to the login page.
navigate(`/app/login`)
return null
}
return <Component {...rest} />
}
const App = () => (
<Layout>
<Router>
<PrivateRoute path="/ddddddddddddddddddd" component={Home} />
<Login path="/" />
</Router>
</Layout>
)
export default App
The paths that you have in your App.js should have /app/ prepended in front of them since your PrivateRoute logic uses that to check for a login. Furthermore what your gatsby-node.js file is really saying is that for routes starting with app it should create a new page. Your src/pages/app.js has the task to define how these pages should be created (since they won't be the usual generated static pages by gatsby)
import React from "react"
import { Router } from "#reach/router"
import Layout from "../components/layout"
import Home from '../components/dashboard/home/container'
import Login from '../components/marketing/home/pulsemetrics'
import { isLoggedIn } from "../services/auth"
console.log('vvvvvvvvvvvvvvvvvvvvv')
const PrivateRoute = ({ component: Component, location, ...rest }) => {
console.log('hjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjjiiiiiiiiiiiiiiiiiii')
if (!isLoggedIn() && location.pathname !== `/app/login`) {
// If the user is not logged in, redirect to the login page.
navigate(`/app/login`)
return null
}
return <Component {...rest} />
}
const App = () => (
<Layout>
<Router>
<PrivateRoute path="/app/home" component={Home} />
<Login path="/app/login" />
</Router>
</Layout>
)
export default App
Read the gatsby client-only routes documentation for reference or have a look at this github issue
I have faced a problem. I am used react-router-dom for routing. It's working well but goBack is not working properly. When I clicked back button it's 1st going to NotFound/Signin page then redirect to back page. How can I overcome this issue?
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import Signin from '../ui/signin/Signin';
import AddEvent from '../ui/events/AddEvent';
import EventView from '../ui/events/EventView';
import NotFound from '../ui/NotFound';
const history = createBrowserHistory();
const privatePages = [
'/events',
'/addevent',
];
const publicPages = ['/', '/signup','/forgotpassword'];
const onEnterPublicPage = () => {
if (Meteor.userId()) {
history.replace('/events');
}
};
const onEnterPrivatePage = () => {
if (!Meteor.userId()) {
history.replace('/');
}
};
export const onAuthenticationChange = (isAuthenticated) => {
const pathname = this.location.pathname;
const isUnauthenticatedPage = publicPages.includes(pathname);
const isAuthenticatedPage = privatePages.includes(pathname);
if (isAuthenticated && isUnauthenticatedPage) {
history.replace('/events');
} else if (!isAuthenticated && isAuthenticatedPage) {
history.replace('/');
}
}
export const routes = (
<Router history = {history}>
<Switch>
<Route
exact path="/events"
component={ListEvents}
onEnter={onEnterPrivatePage} />
<Route
exact path="/addevent"
component={AddEvent}
onEnter={onEnterPrivatePage} />
<Route component={NotFound}/>
<Route
exact path="/"
component={Signin}
onEnter={onEnterPublicPage} />
</Switch>
</Router>
);
In the component :
constructor(props){
super(props);
this.goBack = this.goBack.bind(this);
}
goBack(){
this.props.history.goBack();
// this.props.history.push.go(-1);
}
In the return
<Link
to=""
onClick={this.goBack}
className="back-icon">
Back
</Link>
Its because you are using history.replace('/'). You are replacing, not pushing so there is no previous route.
One possible way is, Instead of using Link, use history.push to change the route dynamically. To achieve that remove the Link component and define the onClick event on "li" or "button". Now first perform all the task inside onClick function and at the end use history.push to change the route means to navigate on other page.
I hope this helps
I have had the same issue and the history.goBack() function doesn't work with <Link /> component, but if you replace it for any other it will work
I want 2 pages in my Chrome extension. For example: first(default) page with list of users and second with actions for this user.
I want to display second page by clicking on user(ClickableListItem in my case). I use React and React Router. Here the component in which I have:
class Resents extends React.Component {
constructor(props) {
super(props);
this.handleOnClick = this.handleOnClick.bind(this);
}
handleOnClick() {
console.log('navigate to next page');
const path = '/description-view';
browserHistory.push(path);
}
render() {
const ClickableListItem = clickableEnhance(ListItem);
return (
<div>
<List>
<ClickableListItem
primaryText="Donald Trump"
leftAvatar={<Avatar src="img/some-guy.jpg" />}
rightIcon={<ImageNavigateNext />}
onClick={this.handleOnClick}
/>
// some code missed for simplicity
</List>
</div>
);
}
}
I also tried to wrap ClickableListItem into Link component(from react-router) but it does nothing.
Maybe the thing is that Chrome Extensions haven`t their browserHistory... But I don`t see any errors in console...
What can I do for routing with React?
I know this post is old. Nevertheless, I'll leave my answer here just in case somebody still looking for it and want a quick answer to fix their existing router.
In my case, I get away with just switching from BrowserRouter to MemoryRouter. It works like charm without a need of additional memory package!
import { MemoryRouter as Router } from 'react-router-dom';
ReactDOM.render(
<React.StrictMode>
<Router>
<OptionsComponent />
</Router>
</React.StrictMode>,
document.querySelector('#root')
);
You can try other methods, that suits for you in the ReactRouter Documentation
While you wouldn't want to use the browser (or hash) history for your extension, you could use a memory history. A memory history replicates the browser history, but maintains its own history stack.
import { createMemoryHistory } from 'history'
const history = createMemoryHistory()
For an extension with only two pages, using React Router is overkill. It would be simpler to maintain a value in state describing which "page" to render and use a switch or if/else statements to only render the correct page component.
render() {
let page = null
switch (this.state.page) {
case 'home':
page = <Home />
break
case 'user':
page = <User />
break
}
return page
}
I solved this problem by using single routes instead of nested. The problem was in another place...
Also, I created an issue: https://github.com/ReactTraining/react-router/issues/4309
This is a very lightweight solution I just found. I just tried it - simple and performant: react-chrome-extension-router
I just had to use createMemoryHistory instead of createBrowserHistory:
import React from "react";
import ReactDOM from "react-dom";
import { Router, Switch, Route, Link } from "react-router-dom";
import { createMemoryHistory } from "history";
import Page1 from "./Page1";
import Page2 from "./Page2";
const history = createMemoryHistory();
const App: React.FC<{}> = () => {
return (
<Router history={history}>
<Switch>
<Route exact path="/">
<Page1 />
</Route>
<Route path="/page2">
<Page2 />
</Route>
</Switch>
</Router>
);
};
const root = document.createElement("div");
document.body.appendChild(root);
ReactDOM.render(<App />, root);
import React from "react";
import { useHistory } from "react-router-dom";
const Page1 = () => {
const history = useHistory();
return (
<button onClick={() => history.push("/page2")}>Navigate to Page 2</button>
);
};
export default Page1;
A modern lightweight option has presented itself with the package wouter.
You can create a custom hook to change route based on the hash.
see wouter docs.
import { useState, useEffect } from "react";
import { Router, Route } from "wouter";
// returns the current hash location in a normalized form
// (excluding the leading '#' symbol)
const currentLocation = () => {
return window.location.hash.replace(/^#/, "") || "/";
};
const navigate = (to) => (window.location.hash = to);
const useHashLocation = () => {
const [loc, setLoc] = useState(currentLocation());
useEffect(() => {
// this function is called whenever the hash changes
const handler = () => setLoc(currentLocation());
// subscribe to hash changes
window.addEventListener("hashchange", handler);
return () => window.removeEventListener("hashchange", handler);
}, []);
return [loc, navigate];
};
const App = () => (
<Router hook={useHashLocation}>
<Route path="/about" component={About} />
...
</Router>
);