React Router redirects all requests to "/" - javascript

Whenever I try to browse path like "/about" which in browser would be like this : "http://localhost:3000/#/about" . I got my home page. React Router doesn't direct me to wanted path.
I use React Router v4.
This is my App.jsx file :
var React = require('react');
var ReactDOM = require('react-dom');
var Router = require('react-router-dom').BrowserRouter;
var {Route,Link, hashHistory, Switch} = require('react-router-dom');
var Main = require('Main');
var Weather = require('Weather');
var About = require('About');
var Examples = require('Examples');
ReactDOM.render(
<Router>
<div>
<Route exact path="/about" component={About} />
<Route exact path="/examples" component={Examples} />
<Route exact path= "/" component={Main} />
</div>
</Router>
,document.getElementById('app')
);
These 2 solutions didn't work:
React Router Default Route Redirect to /home
React Router always redirect me to a different url
And another question: Which version of React Router is better to use? I think v3 is better than v4,due to simplicity.

You are using a Hash router (as I see in your url). So you have to use HashRouter instead of Router.
var React = require('react');
var ReactDOM = require('react-dom');
var {HashRouter, Route,Link, hashHistory, Switch} = require('react-router-dom');
var Main = require('Main');
var Weather = require('Weather');
var About = require('About');
var Examples = require('Examples');
ReactDOM.render(
<HashRouter>
<div>
<Route exact path="/about" component={About} />
<Route exact path="/examples" component={Examples} />
<Route exact path= "/" component={Main} />
</div>
</HashRouter>
,document.getElementById('app')
);

Wrap you routes with <Switch> component.

Right now, it appears you are using the wrong router. You want to use the HashRouter but you are using the BrowserRouter. Try updating your imports like so.
var React = require('react');
var ReactDOM = require('react-dom');
var { Route, Link, HashRouter as Router, Switch } = require('react-router-dom');

Related

Reactjs how to add variable in URL parameter

The link from my backend produce ?id= for my frontend to parse using queryString. Is there a way to get this link to load in the frontend?
http://localhost:3000/resetpassword/?id=61bc1fbe3490be4f3594cc3e/?token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJfaWQiOiI2MWJjMWZiZTM0OTBiZTRmMzU5NGNjM2UiLCJmaXJzdG5hbWUiOiJPY2VhbiIsImxhc3RuYW1lIjoiUnlhbiIsImVtYWlsIjoib2NlYW5yeWFuNzI1QHlhaG9vLmNvbSIsInBob25lTnVtYmVyIjo2MjgxMTYxNTIyNjMyLCJkb2IiOiIyMDAwLTA3LTI1VDAwOjAwOjAwLjAwMFoiLCJwYXNzd29yZCI6IiQyYiQxMCR6Li9hMHFQYVFzdnNCUEtxc2QuaENlWmI3OWpIYW1VdHdXNmVnSEpLLlhndHFGZzV3djJ0bSIsIl9fdiI6MH0.21irj8fCPQFvCqmp-3E9BJmqwVp81gyQxIW5LgFplMg
App.js
import './App.css';
import { BrowserRouter,
Routes,
Route,
} from "react-router-dom"; //v6
import LandingPage from "./pages/LandingPage/LandingPage";
import ResetPwPage from "./pages/ResetPwPage/ResetPw";
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<LandingPage/>}/>
<Route path="/resetpassword/:id/:token" element={<ResetPwPage/>} />
</Routes>
</BrowserRouter>
);
}
export default App;
I tried
<Route path="/resetpassword/?id=:id/?token=:token" element={<ResetPwPage/>} />
But it doesnt work.
I need the link to contain ?id= and ?token= since i need to get the value of id and token in the frontend as required with queryString.
const parsed = queryString.parse(location.search);
console.log(parsed);
//=> {foo: 'bar'}
Any suggestion or alternatives is much appreciated. Thank you!
In react-router-dom the router and routes/paths don't concern themselves with the queryString, they only care about the path part of the URL. In RRDv6 there is a new useSearchParams hook for accessing and reading from the queryString.
path
/resetpassword/?id=61bc1fbe3490be4f3594cc3e&token=eyJ0eX.....
Remove the bits from the path that was trying to read the queryString.
function App() {
return (
<BrowserRouter>
<Routes>
<Route path="/" element={<LandingPage/>} />
<Route path="/resetpassword" element={<ResetPwPage/>} />
</Routes>
</BrowserRouter>
);
}
ResetPwPage
import { useSearchParams } from 'react-router-dom';
...
const [searchParams] = useSearchParams();
...
const id = searchParams.get("id");
const token = searchParams.get("token");

react route using browserhistory changes url but nothing happens

I'm trying to get a react router to work. This is my code:
var hashHistory = require('react-router-dom').hashHistory;
var BrowserRouter = require('react-router-dom').BrowserRouter;
var Route = require('react-router-dom').Route;
var ReactDOM = require('react-dom');
var React = require('react');
var Index = require('./index');
var Login = require('./login');
ReactDOM.render(
<BrowserRouter history={hashHistory}>
<div>
<Route path="/" component={Index} />
<Route path="/login" component={Login} />
</div>
</BrowserRouter>,
document.getElementById('main-content')
);
and then later in my index.js i do this:
<div className="navbar-nav" onClick={() => this.props.history.push('/login')}>
Log in
</div>
This makes the url change to /login but it doesn't render the login file. What is wrong?
It seems like when you switch to /login it matches to /:
<Route path="/" component={Index} />
Try to add exact prop to the route, like this:
<Route exact path="/" component={Index} />
What you can also try to do is to change the matching order:
<Route path="/login" component={Login} />
<Route path="/" component={Index} />
Is your index.js a separate file or component? If so you need to use the router middleware to connect it to react-router.
Either import the Link component and use it directly,
or bind a click handler and wrap withRouter to mount the router calls to the props.
import React from 'react';
import {Link, withRouter} from 'react-router';
class Test extends React.Component {
constructor(props) {
super(props);
this.handleLink = this.handleLink.bind(this);
}
handleLink() {
this.props.history.push('/login')
}
render() {
return (
<div>
<Link to={{pathname: '/login'}}>Link</Link>
<button onClick={this.handleLink}>Click</button>
</div>
);
}
}
export default withRouter(Test);

React-Router Navigating Through Routes Using jQuery

Ok, I have my React-Router working more or less the way I want it but my issue is this: I now need to add a bit of functionality in my JS.
Example: The user enters their details and clicks 'login', I would like my jQuery to check if the credentials are correct and if they are change the route to the home page.
I have no idea, how I would go about this.
This is my React-Router code:
import React from 'react'
import ReactDOM from 'react-dom';
import { Router, Route, hashHistory, Navigation } from 'react-router'
import Login from './login'
import Signup from './signup'
import Home from './home'
ReactDOM.render((
<Router history={hashHistory}>
<Route path="/" component={Login}/>
<Route path="/signup" component={Signup}/>
<Route path="/home" component={Home}/>
</Router>
), document.getElementById("app"))
$("#loginBtn").click(
function(){
var email = $('loginEmail').val();
var pass = $('loginpwd').val();
/* Check to see if credential are correct.
* If so, change to '/home route
*/
}
);
Any ideas would be greatly appreciated. Thanks :)
One way would be the following:
const openAppRoute = (route) => {
// Summary:
// Helper function for developers to navigation
// to a different route programmatically.
hashHistory.push(route);
};
window.openAppRoute = openAppRoute;
$("#loginBtn").click(
function(){
var email = $('loginEmail').val();
var pass = $('loginpwd').val();
/* Check to see if credential are correct.
* If so, change to '/home route
*/
window.openAppRoute("/home");
}
);

React-router not rendering Component

This is a sample code I'm trying to implement. But I can't find the reason why react is not rendering the component. I am including react-router from CDN. Please Help
import { Router, Route, Link, browserHistory } from 'react-router'
var HomePage = React.createClass({
render:function(){
return(
<div>
<h1>Hi World</h1>
</div>
);
}
});
ReactDOM.render(
<Router history={browserHistory}>
<Route path='/home' component={HomePage} />
</Router>
,document.getElementById('mydiv')
);
try to use hashHistory, jsbin example with CDN.
Example with imports
browserHistory requires additional configuration on the server side to serve up URLs.
var ReactRouter = window.ReactRouter;
var Route = ReactRouter.Route;
var Router = ReactRouter.Router;
var Link = ReactRouter.Link;
var hashHistory = ReactRouter.hashHistory;
var HomePage = React.createClass({
render:function(){
return(
<div>
<h1>Hi World</h1>
</div>
);
}
});
ReactDOM.render(
<Router history={hashHistory}>
<Route path='/home' component={HomePage} />
</Router>
,document.getElementById('mydiv')
);

React-router Uncaught TypeError: type.toUpperCase is not a function

I'm using the latest version of react, react-router, gulp and browserify
I got this in beowser console:
Uncaught TypeError: type.toUpperCase is not a function
my code in app.js:
"use strict";
var React = require('react');
var Router = require('react-router');
var Header = require('./components/Header');
var Index = require('./components/Index');
var About = require('./components/About')
var Route = Router.Route;
var IndexRoute = Router.IndexRoute ;
var App = React.createClass({
render: function(){
return (
<div>
<Header />
<div>
{this.props.children}
</div>
</div>
);
}
})
React.render(<Router><Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="about" component={About}/>
</Route>
</Router>, document.getElementById('app'));
Just upgrade your react router version from 0.0.13 to 1.0.0-rc1(beta) coz the below code will only work for 1.0.0 beta version which is mentioned in change log.
React.render(<Router><Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="about" component={About}/>
</Route>
</Router>, document.getElementById('app'));
After upgrading version you have to declare router properly like below.
var React = require('react');
var ReactRouter = require('react-router');
var Router = ReactRouter .Router;
var Route = ReactRouter .Route;
Now router is defined properly. This worked for me..give a try.

Categories