Using React-Router to navigate between components on the same page - reactjs

I'm working on the todo list, where we have one main page with a list of items, and all manipulations with them (creation, editing, viewing) happens through the modal windows, and now I need to add some "routing" for these modal windows (e.g. user inserts some specific URL into browser's address bar and the app should be displayed with opened modal window)
I'm considering adding a hash to the URL, e.g. for the creation it should be "#create-task" and then handle the hash change in the custom useEffect like this:
useEffect(() => {
if (location.hash === 'create-task') {
openCreateTaskModal();
} else if (location.hash === 'view-task') {
openViewTaskModal(id); // "id" also should be parsed from URL
}
}, [location.hash])
What do you think about this solution, maybe there are better ways to implement this?

I think, best practice.
import { Route } from "react-router";
...
return (
<div>
<Route path="/create">
<CreateComponent />
</Route>
<Route path="/view/:id">
<ViewComponent />
</Route>
</div>
);

Related

react-router-dom - how set show on everything except 404?

I want setup aside element in react-router-dom,
which show on everything page, without 404.
Bellow my code:
<>
<aside>
<*Routes*\>
<*Route* *path*="\*" *element*={<*BookSidebar* />} />
</*Routes*\>
</aside>
<*Routes*\>
<*Route* *element*={<*BooksLayout* />}>
<*Route* *index* *element*={<*BookList* />} />
<*Route* *path*=":id" *element*={<*Book* />} />
<*Route* *path*="new" *element*={<*NewBook* />} />
<*Route* *path*="\*" *element*={<*NotFound* />} />
</*Route*\>
</*Routes*\>
</>
At the moment <*Route* *path*="\*" *element*={<*BookSidebar* />} /> , showed on each pages even NotFound, how I can fix it?
Here's my take on this problem.
If I got it right, you want to render <BookSidebar /> everywhere but on the NotFound page.
What you could do is a logic-oriented rendering based on the useLocation() hook provided by that same React Router!
So, first hand, we'll need to render this on each of our page, and what contains each of our page? App.js here.
So, our code on App.js should look more or less like this:
{aside && (
<aside>
<BookSidebar/>
</aside>
)}
This will allow us to render, or not the BookSidebar component based on the aside state.
Let's add that state, and set it to true, as most of the time, it'll be true.
const [aside, setAside] = useState(true);
We're getting there, all that is left is to detect, at each time the user navigates from a page, if he is on the 404 page or not.
And there's nothing much more convenient for that than useEffect.
But, before that, we need to use the useLocation() hook of React Router, which allows us to know where the user is at any given time, because remember, we need to know if he is or not on the 404 Error page!
const location = useLocation();
This needs to run in the App.js, as it's where we render our Route.
useEffect(() => {
console.log("Location changed! We are now in: ", location.pathname);
if (location.pathname === "/error404path") {
console.log("Detected we were in /error404path, hiding Aside.");
setAside(false);
}
}, [location]);
And that's it! Our logical rendering based on the state that we can, on purpose, turn off based on any conditions, is done and working!

React Router history on browser's back button

I have a home component with a link which loads a display component and in display component i have the same link which loads the display component again.
if user clicks the link many times in Display Component then there will be a lot of router history.i want that when a user clicks the browser back button it should load the home component not all the previous history.
when i use history.replace("/"); in Display component with onClick event then it works only one time back.but again back is resulting the previous history of Display Component
Routes.js
import Home from "./Components/Home"
import Display from "./Components/Display"
<Router>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/:city">
<Display />
</Route>
</Switch>
</Router>
Home.js
<Link to ={`/${city}`} onClick={()=>{dispatch(fetchWeather(city)); }}>Search</Link>
Display.js
<Link to ={`/${city}`} onClick={()=>{dispatch(fetchWeather(city)); }}>Search</Link>
Depending on the version of react router you are using you can just add the replace prop on your Link component in the Display.js file to not push new states on the history stack and instead update the current one.
<Link replace to ={`/${city}`} onClick={()=>{dispatch(fetchWeather(city)); }}>Search</Link>
If you're on an older version where this isn't supported what you can do is have a click handler do this for you
// Display.js file
function Display(props) {
// whatever code you have for this file
const handleViewCity = useCallback((event, city) => {
// prevent the default redirect from happening, were going to manage that ourselves
event.preventDefault()
dispatch(fetchWeather(city))
props.history.replace(`/${city}`)
}, [props.history, fetchWeather])
return (
// your jsx
// keep the href so you get browser builtin functionality like right click "open in new window"
<a href={`/${city}`} onClick={(e) => handleViewCity(e, city)}>Search</Link>
)
}
export default withRouter(Display)
To visualize what would be happening here think of history as a stack of locations. (this is a simple example - pseudo code)
history.push('/city1') // ['/home', '/city1']
history.push('/city2') // ['/home', '/city1', '/city2']
history.push('/city3') // ['/home', '/city1', '/city2', '/city3']
Pressing the browser back button fires a window popstate event. Pop being the keyword there. When the browser back button is pressed your history then looks like this ['/home', '/city1', '/city2'], which is why you were seeing different cities from the history.
Instead you want to use replace to achieve the desired effect
history.replace('/city1') // ['/home', '/city1']
history.replace('/city2') // ['/home', '/city2']
history.replace('/city3') // ['/home', '/city3']

How to load a specific component when we click on a Card which takes us to an external page

I have a card item as follows : -
<CardItem
src='images/img-9.jpg'
text='Sentiment Analysis Using CNN'
label='Deep Learning'
path='/cnn-project' />
I have created a route as : -
<Route path='/cnn-project' component={() => { window.open("https://www.w3schools.com"); return null;}}/>
This is working fine .When I click on the card it takes me to the site link in new tab but the component in which I have the card changes and now just footer and the header is visible .Lets say we have card in Project component .
What I want is that after clicking the card it takes me to the site in new tab while Project component is still being displayed in my localhost 3000 ,while currently after clicking it is showing just the footer and header .
How to do that ?
Your window.open works, but simulaneously you're changing your app's path to /cnn-project, which doen't have any mapping since you return null..
Create a component you want displayed at /cnn-project route or simply go back to the previous path, like so:
const BrowserHistory = require('react-router/lib/BrowserHistory').default;
<Route path='/cnn-project' component={() => {
window.open("https://www.w3schools.com");
BrowserHistory.goBack();
return null;}}/>
edit
Just switch the Route prop from component to render and move this window.open to your new component's componentDidMount.
<Route path='/cnn-project' render={() => <MyNewComponent />} />
class MyNewComponent extends Component {
componentDidMount() {
window.open("https://www.w3schools.com");
}
...
}

React Router: navigate to /compose/tweet but keep orthogonal previous route (like: /notifications) mounted

I am seeking to recreate a pattern with React Router. It is best described by the Twitter example: as you hit the Tweet button, the browser navigates to /compose/tweet, mounting the composer component. However, and that's the key, the previous route (/home, /explore, /notifications, /messages) is kept mounted despite the route change. How do you do that?
This could be called bidimensional routing: the /compose/tweet route is kept orthogonal with respect to the other routes that render the main view. The other routes are hidden (i.e., not in the address bar any longer) upon navigating to /compose/tweet, thereby rendering two independent routes (say, /notifications and /compose/tweet) at once.
My actual example: I need to show a user settings menu (/user/menu) as a large sidebar, but I do not want that to change whether the user was navigating / (the homepage), /faq, /contact, etc. Based on my current understanding of React Router, as soon as you hit /user/menu, any other route (take /faq as an example) would be unmounted based on route match.
Caching the previous route (e.g., Redux, which I'm using extensively already) does not seem feasible, since, even though I would be able to redirect the user to the previous route upon exiting /user/menu, React would still be unmounting components, in fact showing the homepage in the background until the user exits /user/menu & gets redirected to where they were at, which is not the intended behaviour. I would want the rest of the page to stay there with the rendered components, just the way Twitter does.
Am I overlooking anything? Is this an easy pattern and I am missing something?
Note: it's a SSR isomorphic app, but I guess/hope that won't change things.
Despite Adam Abramov's suggestion to keep React Router as the source of truth for whatever can be passed as route, and avoid deep integrations between Router and Redux, I found myself having to use Redux as the main source of truth in this (important) use case. I still wanted to have Route components for SSR and SEO purposes.
So, I created my own MultidimensionalSwitch and MultidimensionalRoute components to solve this use case. If a MultidimensionalSwitch is mounted, it will render the components at their subroutes, but if none of them is matched, it will render them based on another dimension, which is provided by Redux at an additional alt property of the corresponding MultidimensionalRoute.
Here below is some code, feel free to answer/ask should you need more info about it.
Main
class _Main extends Component {
render() {
const {menuOpen,selected} = this.props;
return (
<Fragment>
<Route exact path={exactRoutes.ROOT} component={() => <Redirect to={selected?exactRoutes[selected]:exactRoutes.HOME} />} />
<Header />
<Route path={nestedRoutes.AUTH+routeParams.LOGIN_SIGNUP.key} component={ScreenAuth} />
<Route path={exactRoutes.USER_MENU} component={ScreenUser} />
{!menuOpen?"":<ScreenMenu />}
<ScreenMain>
<MultidimensionalSwitch>
<MultidimensionalRoute path={exactRoutes.HOME} alt={selected===guestMenuOption.HOME} component={GuestHome} />
<MultidimensionalRoute path={exactRoutes.USER} alt={selected===guestMenuOption.USER} component={User} />
<MultidimensionalRoute path={exactRoutes.VISION} alt={selected===guestMenuOption.VISION} component={GuestVision} />
<MultidimensionalRoute path={exactRoutes.FAQ} alt={selected===guestMenuOption.FAQ} component={GuestFaq} />
<MultidimensionalRoute path={exactRoutes.INFOGRAPHICS} alt={selected===guestMenuOption.INFOGRAPHICS} component={GuestInfographics} />
<MultidimensionalRoute path={exactRoutes.BLOG} alt={selected===guestMenuOption.BLOG} component={GuestBlog} />
<MultidimensionalRoute path={exactRoutes.CONTACT} alt={selected===guestMenuOption.CONTACT} component={GuestContact} />
</MultidimensionalSwitch>
<Footer />
</ScreenMain>
<Flare />
</Fragment>
);
};
}
const mapStateToProps = state => ({
menuOpen: state.client.guest.menuOpen,
selected: state.client.guest.guestMenuOption,
});
const Main = withRouter(connect(mapStateToProps,{})(_Main));
export default Main;
MultidimensionalSwitch
class _MultidimensionalSwitch extends Component {
render() {
return (
<Fragment>
<Switch>
{this.props.children}
{this.props.children.map(child => !child.props.alt?"":<Route path={nestedRoutes.ROOT} component={child.props.component} />)}
</Switch>
</Fragment>
);
}
}
const mapStateToProps = state => ({
selected: state.client.guest.guestMenuOption,
});
const MultidimensionalSwitch = withRouter(connect(mapStateToProps,{})(_MultidimensionalSwitch));
export default MultidimensionalSwitch;
MultidimensionalRoute
class _MultidimensionalRoute extends Component {
render() {
const {path,component} = this.props;
return (
<Fragment>
<Route exact path={path} component={component} />
</Fragment>
);
}
}
const mapStateToProps = (state,ownProps) => ({
path: ownProps.path,
component: ownProps.component,
});
const MultidimensionalRoute = withRouter(connect(mapStateToProps,{})(_MultidimensionalRoute));
export default MultidimensionalRoute;

Set state property from URL using react-router

I have a container component with a modal in it that is opened and closed based on a state property.
I want to control this via the URL, i.e. I want to have
/projects - the modal is NOT open
/projects/add - the modal IS open
As well as being able to link directly to it, I want the URL to change when I click on links within the main container to open the modal.
Can someone explain how I could do this, or point me in the right direction of a good tutorial?
NOTE: This way is not perfect. Even more it's rather antipattern than pattern. The reason I publish it here is it works fine for me and I like the way I can add modals (I can add modal to any page and in general their components don't depends on the other app in any way. And I keep nice url's instead of ugly ?modal=login-form). But be ready to get problems before you find everything working. Think twice!
Let's consider you want following url's:
/users to show <Users /> component
/users/login to show <Users /> component and <Login /> modal over it
You want Login to not depend on Users in anyway, say adding login modal to other pages without pain.
Let's consider you have kinda root component which stands on top of other components. For example Users render may look something like this:
render() {
return (
<Layout>
<UsersList />
</Layout>
);
}
And Layout's render may look something like this:
render() {
return (
<div className="page-wrapper">
<Header />
<Content>
{this.props.children}
</Content>
<Footer />
</div>
);
}
The trick is to force modal's injection to <Layout /> every time we need it.
The most simple approach is to use flux for it. I'm using redux and have ui reducer for such page meta-information, you can create ui store if you use other flux implementation. Anyway, final goal is to render modal if <Layout />'s state (or even better props) contains modal equal to some string representing modal name. Something like:
render() {
return (
<div className="page-wrapper">
<Header />
<Content>
{this.props.children}
</Content>
{this.props.modal ?
<Modal key={this.props.modal} /> :
null
}
<Footer />
</div>
);
}
<Modal /> returns modal component depends on given key (In case of our login-form key we want to receive <Login /> component).
Okay, let's go to router. Consider following code snippet.
const modal = (key) => {
return class extends React.Component {
static displayName = "ModalWrapper";
componentWillMount() {
// this is redux code that adds modal to ui store. Replace it with your's flux
store.dispatch(uiActions.setModal(key));
}
componentWillUnmount() {
store.dispatch(uiActions.unsetModal());
}
render() {
return (
<div className="Next">{this.props.children}</div>
);
}
}
};
...
<Route path="users" component={Next}>
<IndexRoute component={Users}>
<Route path="login" component={modal('login-form')}>
<IndexRoute component={Users} />
</Route>
</Route>
(Don't care about Next - I add it here for simplicity. Imagine it just renders this.props.children)
modal() function returns react component that triggers change in ui store. So as soon as router gets /users/login it adds login-form to ui store, <Layout /> get it as prop (or state) and renders <Modal /> which renders corresponding for given key modal.
To programmatically assess to a new URL, pass the router to your component and use push. push for example will be call in the callback trigger by the user action.
When setting your router set a route to /projects/:status. then, in your component route, you can read the value of status using this.props.param.status. Read "whats-it-look-lik" from react-router for an example.

Resources