Hash Router back button with React Router v4 - javascript

I'm using HashRouter to setup my App like so:
import {HashRouter as Router, Route, Switch, Link} from 'react-router-dom';
const Routing = () => (
<Router>
<div>
<Route exact path ="/" component = {App} />
<Route path ="/about" component = {About} />
</div>
</Router>
)
It works great, but when I click a link to go to /about and then hit the back button nothing happens. How do I make it so my internet browser's back button will take me back to the previous page? The app is built using create-react-app if that makes a difference.

Use Switch
Switch is unique in that it renders a route exclusively. In
contrast, every Route that matches the location renders inclusively.
This means that the way you are doing it all routes are being rendered because they match.
If the URL is /about, then About, User, and NoMatch will all
render because they all match the path. This is by design, allowing us
to compose Routes into our apps in many ways, like sidebars and
breadcrumbs, bootstrap tabs, etc.
Now, if we're at /about, Switch will start looking for a matching
Route. Route path="/about" will match and Switch will stop
looking for matches and render About
Your code should look like this
import {HashRouter as Router, Route, Switch, Link} from 'react-router-dom';
const Routing = () => (
<Router>
<Switch>
<Route exact path ="/" component = {App} />
<Route path ="/about" component = {About} />
</Switch>
</Router>
)

Related

How to implement links with redirect in next.js?

I have the following react component which I am trying to implement in next.js.
React component:
import React from "react";
import { Route, Switch, Redirect, withRouter } from "react-router-dom";
import Dashboard from "../../pages/dashboard";
import Profile from "../../pages/profile";
function Layout(props) {
return (
<>
<Switch>
<Route
exact
path="/"
render={() => <Redirect to="/app/dashboard" />}
/>
<Route path="/app/dashboard" component={Dashboard} />
<Route path="/app/profile" component={Profile} />
</Switch>
</>
);
}
export default withRouter(Layout);
As I am very new to next. j's, I am not sure on, how can I handle the routes with redirect in next.js similar to above react component code.
Any help is appreciated?
You are using React-Router with NextJS which is possible but not the best practice.
NextJS router is a pretty complicated thing as it handles ClientSide and ServerSide routing simultaneously.
your /app/dashboard and /app/profile pages should render properly. If you want to redirect / to /app/dashboard you can use this trick inside the getInitialProps of the pages/index.js file.

Creating dynamic Link with some text before it

I was building a search engine for custom project.
There I have a search bar from where user can search.
When the user searches, I want the given link to work as it works in case of google
www.google.com/ search? queryRelatedInfo
Notice the search? and then whatever query/parameter/ID
for this I tried something like this in
import React, {Component} from 'react';
import {
BrowserRouter,
Route,
Switch,
Redirect,
} from 'react-router-dom';
import SearchScreen from "./container/searchScreen.js"
import HomeScreen from "./container/home.js";
class route extends Component {
render () {
return (
<BrowserRouter>
<div>
<Switch>
<Route path ="/" exact render ={(props) => <HomeScreen {...props}/>} />
<Route path ="/search?:id" exact render ={(props) => <SearchScreen {...props}/>} />
</Switch>
</div>
</BrowserRouter>
)
}
}
export default route
Notice, <Route path ="/search?:id" above.
Unfortunately this didn't worked out.
I understand that <Route path ="/:id" works but how can i make <Route path ="/search?:id to work i.e how can I make some link like http://localhost:3000/search?9e9e to work
I think this is related with historyApiFallback. That parameter;
(https://webpack.js.org/configuration/dev-server/#devserver-historyapifallback)
When using the HTML5 History API, the index.html page will likely have to be served in place of any 404 responses. devServer.historyApiFallback is disabled by default. Enable it by passing:
module.exports = {
//...
devServer: {
historyApiFallback: true
}
};
Your react app is a single page application. So all path except home path actually is an virtual path, they are not physically exist. The paths must routed to home path. So react-router can manage.
you don't need to put the path like this /search?:id, just put it search
<Route path ="/search" exact render ={(props) => <SearchScreen {...props}/>} />
then inside your SearchScreen component, get the value of search parameter from the URL, check this issue will help.
after the user make search, pass the value like this /search?s=value_here

Get React router to cause a re-render

I have mixed content on my homepage. The user specific content is an edit button next to their own content.
When the user logs out via a logout route this code gets executed:
import React from 'react'; // needed
import ReactDOM from 'react-dom';
import Home from './components/layout/Home.js';
import Login from './Login/Login';
import PollDetails from './components/layout/PollDetails.js';
import EditPoll from './components/presentation/EditPoll.js';
import CreatePoll from './components/presentation/CreatePoll';
import Container from './components/containers/Container.js';
import {Route,Router,browserHistory,IndexRoute} from 'react-router';
import Auth from './utils/Auth';
const mountNode = document.getElementById('root');
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={Container} >
<IndexRoute component={Home} />
<Route path="login" component={Login} />
<Route path="logout" onEnter={(nextState, replace) => {
Auth.deauthenticateUser();
console.log('Logging out src/app.js');
Auth.clearCookie();
// change the current URL to /
replace('/');}} />
<Route path="Polldetailfull/:id" component={PollDetails} />
<Route path="Editthepoll/:id" component={EditPoll} />
<Route path="createPoll" getComponent={(location, callback) => {
if (Auth.isUserAuthenticated()) {
callback(null, CreatePoll);
} else {
callback(null, Home);
}
}} />
</Route>
</Router>,mountNode);
However, the replace('/'); sends you back to the home page but doesn’t re-render any components. Note there is no state to change here. Do I need a state to force the re-render?
Note, if you press refresh on the browser the desired behaviour happens. I tried looking on React Router's code but could not find much about events. To be honest, I don't fully understand onEnter={(nextState, replace) =>
You could use location.reload() to cause it to re-render
onEnter -> this function use when component going to render on browser.
For your idea, You need to use route the component based log details in component life cycle of particular components.below code to be use in path component life cycle(componentWillMount or componentDidMount) and route the page as want .
browserHistory.push('/location-path-name');
call the component based log details in router like below sample
<Route path="createPoll" component={Auth.isUserAuthenticated() ? CreatePoll : Home}/>

Router.match is not been called on every route change

I have server side rendering app and using react-router for routing. I was using Router.Run Before as the method is no more I am using Router.Match.Previously when there was route change router.run used to be called but same behavior is not happening in the router.match. Is there any reason behind it?
I have defined my router in entry module defined below and it will go to Layout component to look for route paths:
import { Router, Route, IndexRoute, hashHistory } from "react-router";
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={Layout}>
//<IndexRoute component={Featured}></IndexRoute>
<Route path="archives" name="archives" component={Archives}></Route>
<Route path="settings" component={Settings}></Route>
<Route path="featured" component={Featured}></Route>
</Route>
</Router>,
document.getElementById('app'));
Layout component will bind the path defined in router to different components in Layout Component
import { Link } from "react-router";
class Layout extends React.Component(
render(){
return(
{this.props.children}
<li><MenuItem><Link to="archives">archives</Link></MenuItem></li>
<li><MenuItem><Link to="settings">settings</Link></MenuItem></li>
<li><MenuItem><Link to="featured">featured</Link></MenuItem></li>
)
}
);
You can define any action for your route components.its working fine for me

Access to router directly by typing it's address on the address bar in react-router

There is two "main" way to use react-router (V4); The first way is using hash router which you can access directly to an address by typing it on browser's address bar but you must add a # to URL, another way is using BrowserRouter which has a pretty and user-friendly URL structure but you can't directly type the address to render the route.
How I can config HashRouter to work without # or config BrowserRouter to work with directly URL typing, too? Is it possible with .htaccess? How?
const React = require('react');
const ReactDOM = require('react-dom');
import { HashRouter as Router, Route, Link} from 'react-router-dom';
const routes = (
<Router forceRefresh={false}>
<div>
<Route exact path="/" component={Firstpage}/>
<Route exact path="/projects" component={Projectslist}/>
</div>
</Router>
);
ReactDOM.render(routes, document.getElementById('app'));
[In this type it works with a # mark. e.g.: localhost:2000/#/projects ]
Another type:
const React = require('react');
const ReactDOM = require('react-dom');
import { BrowserRouter as Router, Route, Link} from 'react-router-dom';
const routes = (
<Router forceRefresh={true}>
<div>
<Route exact path="/" component={Firstpage}/>
<Route exact path="/projects" component={Projectslist}/>
</div>
</Router>
);
ReactDOM.render(routes, document.getElementById('app'));
[And in this type it works well without a # mark, but it's not possible to load it directly on the browser's address bar.]
If you are using webpack-dev-server, you need to set historyApiFallback: true in your config file.
https://webpack.js.org/configuration/dev-server/#devserver-historyapifallback

Categories