6

Can anyone explain to me how Routing works in Reactjs?

browserHistory.push('/location')

only updates the URL bar and doesn't redirect to it.

browserHistory.goBack()

works but only when the page has been visited before, hence the name. Which makes it difficult for me to understand how browserHitory.goForward() works?

I have been trying to redirect to dashboard after a successful login. That's it.

From what I have read, React does not allow reloading a page. It will show a cannot GET /path error if we try to refresh the page or write the address in the url; unless the request is made on the server. I tried to create routes on server, but cannot get the syntax as to how I achieve it. I have only coded in Node to the extent of sending res.send() to the client app. How do I render that path? Because rendering to that path would mean that the Node's App.js has the view engine of the React app. I don't know if it's clear enough, but any advice would be helpful. Thanks.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202
  • take a look at [react-router](https://reacttraining.com/react-router/web/guides/quick-start) – bntzio May 01 '17 at 04:52

3 Answers3

1

first of all define all urls in router that is You can watch these two videos for complete routing part1 part2

You forgot to add use browserHistory.replace('/location') another thing is that dont include / in child routes for example use like this <Route path='submissions' component={Submissions} />

export default ( <Router history={browserHistory}> 
<Route component={App}> 
<Route path='/' component={Home} /> 
<Route path='/submissions' component={Submissions} />
<Route path='/location' component={Location} /> 
<Route path='/login' component={Login} /> 
<Route path='/dashboard' component={Member} /> 
</Route> </Router> );
Naveed Aheer
  • 1,715
  • 6
  • 25
  • 40
0

You're probably more generically wondering how single page applications routing works.

There are endless resources about this subject on the web.

This is a reactish article I have immensely appreciated: https://hackernoon.com/routing-in-react-the-uncomplicated-way-b2c5ffaee997

Andrea Carraro
  • 9,731
  • 5
  • 33
  • 57
  • Really helpful. Thanks. Routing works absolutely fine in Angular, there's no hassle in it. React however is giving me some hard time. – Amrita Sharma May 01 '17 at 05:10
0

Index.js

import { BrowserRouter } from "react-router-dom";
ReactDOM.render(
  <BrowserRouter>
    <App />
  </BrowserRouter>,
  document.getElementById("root")
);

Component BrowserRouter wraps the history object in the browser and passes it to down to component tree. Anywhere in the component tree we are able to use the history object. Then we need to register our routes in app.js.

app.js

import { Route, Redirect, Switch } from "react-router-dom";
class App extends Component {
  render() {
    return (
      <div>
        <NavBar />
        <main className="container">
          <Switch>
            <Route path="/not-found" component={NotFound} />
            <Route path="/register" component={RegisterForm} />
            <Route path="/login" component={LoginForm} />
            <Redirect from="/" exact to="/home" />
            <Redirect to="/not-found" />
          </Switch>
        </main>
      </div>
    );
  }
}

export default App;

If we did not use the "Switch", react would read "/" first and since that route is returning homepage, every route would return homepage too. For example,

<Route path="/register" component={RegisterForm} />

this would return "RegisterForm" and homepage. With using "Switch" we have to order our routers from most specific one to the most generic one. Means “/” should be in the bottom.

Now we have an issue. Every time we navigate from one page to another, we will have http requests from server. All of the components are part of the bundle and already downloaded when app loads so there is no need to reload them. Instead of reloading entire page with all assets, we should only update what we have in the content area. Solution is all the anchors should be replaced with “Link” from react-router-dom. Link component doesn't have “href” attr instead has “to”. Every time we click on links, “Link” has a click event. It will preventDefault(). So lets create a simple button with Link:

import { Link } from "react-router-dom";

  <div className="col">
      <Link to="/products/new" className="btn btn-primary my-2">
        New Products
      </Link>
 </div>

In the beginning I said BrowserRouter wraps the history object in the browser and passes it to down to component tree. So we access it by "Route". When we registered our routes, "Route" automatically injects "History, Location, Match" props into the components. If you need to pass additional props to routed components; instead of component attribute we should use render attribute.

<Route path="/products" render={(props) => <Products sortBy= “newest” {...props} /> }  />

Note that If we didnt pass “props”, History,Location and Match would disappear.

When user clicked on a button or submit a form, we wanna navigate it to a different page. “History” object is responsible for navigation: go back, go forward, push and replace

PUSH: push method will add a new address in the browser history, so you click the back button and you go back to where you were.

REPLACE:replaces the current address, so we will not have history.

handleSave = ( )  => { this.props.history.push ("/products"); };

we can read route parameters and passed them to a component using the “match” object. So we can render this info in our ProductDetails page as below.

<div>
        <h2> productDetails-{this.props.match.params.id} </h2>
    </div>

Query string parameters are in “location” object.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Yilmaz
  • 35,338
  • 10
  • 157
  • 202