简体   繁体   中英

React router anchor link

I use react for some component and I have a navigation menu outside the react root.

I want to change react component inside the root when I click to menu links.

I search and see react-router is a solution but I don't know how to do this.

Also note I don't want to use Hash urls.

Here is example of my codes

<div class="menu">
<a href="page2">page 2</a>
</div>
<div class="react-root"></div>

And I call react render for react-root div only.

How can I tell react to change the component when I click on page 2? Is react-router is good solution and how Can I do it with react router?

The point of using react-router is generally to have page not refreshed as user navigates. If you bring your nav links inside the react app you will get to experience single page application without refreshing the page.

Otherwise, you can have something like this:

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

const App = () => <div>Home Page</div>;
const App2 = () => <div>Page 2</div>;

const routing = (
  <Router>
    <div>
      <Route exact path="/" component={App} />
      <Route path="/page2" component={App2} />
    </div>
  </Router>
);

ReactDOM.render(routing, document.getElementById("react-root"));

But better way is something like this:

const App = () => <div>Home Page</div>;
const App2 = () => <div>I am Page 2</div>;

const routing = (
  <Router>
    <div class="menu">
      <Link to="/">Home Page</Link>
      <Link to="/page2">Page 2</Link>
    </div>
    <div>
      <Route exact path="/" component={App} />
      <Route path="/page2" component={App2} />
      <Route path="/page3" component={App} />
    </div>
  </Router>
);

ReactDOM.render(routing, document.getElementById("react-root"));

Here is the code sandbox link where you can see the difference between two https://codesandbox.io/s/holy-wind-olex5?fontsize=14&hidenavigation=1&theme=dark

I solved it by getting helps from this question How to get history on react-router v4?

Here is my code

document.getElementById("test").onclick = function(e){
  e.preventDefault();
  history.push("/page2")
}

and it's working!

https://codesandbox.io/s/inspiring-goldberg-utryd?fontsize=14&hidenavigation=1&theme=dark

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