简体   繁体   中英

React Router dom not routing

I am building simple application on Codesandbox.io and I am struggling with doing routes, actually I am following tutorials and it just doesn't work with me.

Here is my code, it contains of four files (index, Start, Home and Nav), These files has nothing except just to show a word of (Home or start here), here is my main file (index.js)

import React from "react";
import ReactDom from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";

import "./styles.css";
import "./news.css";
import Nav from "./Nav";
import Home from "./Home";
import Start from "./Start";

class Index extends React.Component {
  render() {
    return (
      <div>
        <div className="container"> start here </div>
        <Router>
          <div>
            <Nav />
            <Route exact path="/" Component={Index} />
            <Route path="/Home" Component={Home} />
            <Route path="/Start" Component={Start} />
          </div>
        </Router>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDom.render(<Index />, rootElement);

This is my Home.js

import React from "react";

class Home extends React.Component {
  render() {
    return <div>home</div>;
  }
}

export default Home;

Nav.js

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

const Nav = () => {
  return (
    <div>
      <Link to="/">Home</Link>
      <Link to="/Home"> home 2 class </Link>
      <Link to="/Start"> Start </Link>
    </div>
  );
};

export default Nav;

Start.js

import React from "react";

class Start extends React.Component {
  render() {
    return <div>start here</div>;
  }
}

export default Start;

You were close, you have Component={Home} capitalized, you should have component lower case, like so.

I can't seem to edit your sandbox, as Index is breaking the code for me, however, in general, that seems to be your issue.

Alternatively, you could have tried to use the render method to display the corresponding components - Route Render Methods

Cheers! Jimmy

You missed switch , you have to use switch to route.

import switch like this.

import { BrowserRouter as Router, Route, Switch  } from "react-router-dom";

Then update render with switch

  <Router>
    <Switch>
        <div className="container">
            <Nav />
            <Route exact path="/" Component={Index} />
            <Route path="/Home" Component={Home} />
            <Route path="/Start" Component={Start} />
        </div>
    </Switch>
</Router>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM