LK10
LK10

Reputation: 157

How To Link To Another Page in React?

What I'm trying to do: I'm trying to get my React Web-App NavBar to link to other pages inside my app.

What I've tried:

  1. Inside my App.js file, I've set up React-Router-Dom as you can see.
  2. I've also inserted the links inside my NavBar
  3. Now, I face a problem when looking at the site on my local server. (See screenshot)

Here's the code for App.js

import React from "react"
import NavBar from "./NavBar"
import Dashboard from "./Dashboard"
import {BrowserRouter as Router, Switch, Route} from "react-router-dom";

function App() {
    return (
        <Router>
        <div>
            <NavBar />
            <Route path="/dashboard" component={Dashboard} />
        </div>
        </Router>
        )
}

export default App

Here's the code for the NavBar

import React from "react"
import "./Style.css"
import { link } from 'react-router-dom'

class NavBar extends React.Component {
    render() { return (

        <nav>
            <h1 className="h1">Hello</h1>
            <ul>
                <link to={"./Dashboard"}>
                    <li>Dashboard</li>
                </link>
            </ul>
        </nav>
    ) 
    }
}

export default NavBar

Here is a screenshot of the error: enter image description here

Upvotes: 9

Views: 101853

Answers (4)

Ahmad Khalid
Ahmad Khalid

Reputation: 1

In App.js, use

<main>
        <Switch>
          <Route exact path="/" component={HomeScreen}/>
          <Route exact path="/product/:id" component={ProductScreen}/>
          <Route exact path="/cart" component={CartScreen}/>
          
        </Switch>
      </main>

Upvotes: 0

Naresh
Naresh

Reputation: 45

In app.js file : add Switch Router as shown below and add exact word to route

 return (
    <Router>
    <div>
        <NavBar />
         <Switch>
        <Route exact path="/dashboard" component={Dashboard} />
       </Switch>
    </div>
    </Router>
    )

export default App

In navbar file: do changes acc.

return (

    <nav>
        <h1 className="h1">Hello</h1>
        <ul>
              <li><link to="/dashboard">Dashboard<link></li>
        </ul>
    </nav>
) 

Note : its not /Dashboard its /dashboard as in route u mentioned in that way

export default NavBar

Upvotes: 0

radulle
radulle

Reputation: 1515

Link component must start with capital letter L in both import and JSX.

  import { Link } from 'react-router-dom'
  
  <Link to={"./Dashboard"}>
    Dashboard
  </Link>

Read more at https://reactrouter.com/web/api/Link, there are a few examples too.

BTW: Link should be inside li

Upvotes: 5

Mohammad Faisal
Mohammad Faisal

Reputation: 2363

you are using link the wrong way


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

<Link to="/Dashboard"> Dashboard </Link>

use this and see if it works

Upvotes: 12

Related Questions