How to navigate to a new page react router v4

15,374

You already had the imports in this.

import {
  BrowserRouter as Router,
  Link,
  Route
} from 'react-router-dom'

However, I would remove all of the routings in your CyptoList page and just make that CyptoList a component.

Now, you want to use those Links in your code to navigate between pages you need to make a place that you want to display the links in.

const Header = () => (
    <nav>
        <ul>
            <li><Link to='/'>CryptoList</Link></li>
            <li><Link to='/currency'>Currency</Link></li>
        </ul>
    </nav>
)

If in your CyptoList page you can just put the header in there like this <Header />

Now, the next part, the Router, you might want to make a new Router.js file or separate it. Or you could do something like this.

// Routes.js
import React from 'react';
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import CryptoList from './CryptoList';  // or whatever the location is
import Currency from './Currency'; // or whatever the location is

export default () => (
<BrowserRouter>
    <Switch>
      <Route exact path="/" component={CryptoList}/>
      <Route path="/currency" component={Currency}/>
    </Switch>
</BrowserRouter>
);

Then when you want to include your Routes as you saved it in the Routes.js file you can just do this.

import Routes from './Routes';

and use it by doing this...

<Routes />

You can always refer to this example on medium with a link to a CodeSandbox and CodePen. https://medium.com/@pshrmn/a-simple-react-router-v4-tutorial-7f23ff27adf

Share:
15,374
Thidasa Pankaja
Author by

Thidasa Pankaja

Passionate Software Engineer at Twire working towards achieving professional goals, with an active drive to learn new technologies. Skilled in JavaScript, React, Go, PostgreSQL etc. Strong engineering professional with a Bachelor of Science (Hons) focused in Information Technology from University of Moratuwa.

Updated on July 23, 2022

Comments

  • Thidasa Pankaja
    Thidasa Pankaja almost 2 years

    I'm building a crypto currency market app as an to practice reactjs. When app starts list of currencies with some properties will be shown as a list. I need to navigate to a different page (new page - Currency component) without loading the component on the bottom of current page. At the moment I was able to render it in the bottom of the page. But that's not what I need.

    Is there any other way than which is mentioned in Route to different page[react-router v4] ? Because I need to pass the clicked object (currency) to the new component (Currency)

    Here's my CryptoList component currency_main.js

    import React, { Component } from 'react';
    import {
      Table,
      TableBody,
      TableHeader,
      TableHeaderColumn,
      TableRow,
      TableRowColumn,
    } from 'material-ui/Table';
    import Currency from './currency';
    import {
      BrowserRouter as Router,
      Link,
      Route
    } from 'react-router-dom'
    
    class CryptoList extends Component {
      constructor(props){
        super(props);
        this.state = {
          currencyList : [],
          showCheckboxes : false,
          selected : [],
          adjustForCheckbox : false
        }
      };
    
      componentWillMount(){
        fetch('/getcurrencylist',
        {
            headers: {
              'Content-Type': 'application/json',
              'Accept':'application/json'
            },
            method: "get",
            dataType: 'json',
        })
        .then((res) => res.json())
        .then((data) => {
          var currencyList = [];
          for(var i=0; i< data.length; i++){
            var currency = data[i];
            currencyList.push(currency);
          }
          console.log(currencyList);
          this.setState({currencyList})
          console.log(this.state.currencyList);
        })
        .catch(err => console.log(err))
      }
    
      render(){
        return (
          <Router>
            <div>
              <Table>
               <TableHeader
                 displaySelectAll={this.state.showCheckboxes}
                 adjustForCheckbox={this.state.showCheckboxes}>
                 <TableRow>
                   <TableHeaderColumn>Rank</TableHeaderColumn>
                   <TableHeaderColumn>Coin</TableHeaderColumn>
                   <TableHeaderColumn>Price</TableHeaderColumn>
                   <TableHeaderColumn>Change</TableHeaderColumn>
                 </TableRow>
               </TableHeader>
               <TableBody displayRowCheckbox={this.state.showCheckboxes}>
                 {this.state.currencyList.map( currency => (
                   <TableRow key={currency.rank}>
                     <TableRowColumn>{currency.rank}</TableRowColumn>
                     <TableRowColumn><Link to='/currency'>{currency.name}</Link></TableRowColumn>
                     <TableRowColumn>{currency.price_btc}</TableRowColumn>
                     <TableRowColumn>{currency.percent_change_1h}</TableRowColumn>
                   </TableRow>
                 ))}
               </TableBody>
             </Table>
             <div>
               <Route path='/currency' component={Currency} />
             </div>
            </div>
          </Router>
        );
      }
    
    }
    
    export default CryptoList;
    

    And here's my Currency component currency.js

    import React, { Component } from 'react';
    
    class Currency extends Component {
    
      componentWillMount(){
        console.log(this.props.params);
      }
    
      render(){
        return (
          <div>
            <h3>
              This is Currency Page !
            </h3>
          </div>
        );
      }
    }
    
    export default Currency;
    

    And here's the currency component which I need to render into a new page when I click currency name in the currency_main component (Which is in second <TableRowColumn>).

    I'm bit new to react and tried react-router in a tutorial only and it was rendering a page as a part of currenct page only.

    So how can I go to a new page using react-router v4 ?

    P.S : I've uploaded the image. As an example if click on Ethereum I need to render the Currency component as a new page.

    enter image description here

    And this should be resulted as the output when I click on Ethereum (as an example) instead of rendering This is Currency Page ! on the same component CryptoList. enter image description here

  • Thidasa Pankaja
    Thidasa Pankaja about 6 years
    Thanks, I already referred the medium article. In both the article and your answer I should select which Component to render. But that's not what I need. I need to click on a currency and then render a new page (which includes the details of the currency) . I've uploaded an image where I need to click the new page to render.
  • donlaur
    donlaur about 6 years
    OK, but your currency page only says "This is Currency Page !". Do you want this to be dynamic based on what the user clicks?
  • Thidasa Pankaja
    Thidasa Pankaja about 6 years
    At the moment I'm trying to get it rendered. But I need to pass the currency object (which includes the data showed in the row and some more which includes in the object) as a props to the Currency component.
  • donlaur
    donlaur about 6 years
    Refer back to that Medium Article and in your Route you would want something like this. <Route path='/currency/:id' component={Currency}/> where the id is the identifier of that row. I am currently unsure what is in your JSON file so hard to let you know exactly.
  • Thidasa Pankaja
    Thidasa Pankaja about 6 years
    Yes, I think I'd be able to pass the object in the route. But here what I need is to render Currency component (yes, at the moment it's only This is Currency Page !) to render as a new page instead rendering it bottom of the current page
  • donlaur
    donlaur about 6 years
    Your Link would be dynamic as well. Maybe something like this. <Link to={/currency/${currency.id}}>{currency.name}</Link>
  • donlaur
    donlaur about 6 years
    It removed the backticks. You might want to watch the following video for more clarity. scotch.io/courses/using-react-router-4/route-params
  • Thidasa Pankaja
    Thidasa Pankaja about 6 years
    Thanks, but at the moment my problem is to rendering the component into a new page instead of rendering it on the bottom. Thanks for the info about passing parameters on the route. But even if I get the data into Currency component it'll render at the bottom of the page not in a new page right ?
  • donlaur
    donlaur about 6 years
    You can put it wherever you want to call the component. It doesn't have to be at the bottom.
  • Thidasa Pankaja
    Thidasa Pankaja about 6 years
    Seems like my question is confusing. I edited the question (added another screenshot) of what I need to get. ( I need to render Currency component which displays This is Currency Page ! ** on a **NEW PAGE instead of the same page. Not bottom, not top, not anywhere on the same page but on a new page.
  • donlaur
    donlaur about 6 years
    Same answer as before. It doesn't matter where you put it. You have to think as a modular design when you are saying component. Want a new page, make a ViewCurrency.js and register as a component. Call your header and your routes. Pull out your JSON data using the parameters after linking via /currency/${currency.id}. If you are confused you can make a codepen and I can walk you through it.