0

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?

Ali Akbar Azizi
  • 3,272
  • 3
  • 25
  • 44

2 Answers2

0

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

bUff23
  • 332
  • 2
  • 16
  • I want to page not refreshing, the main reason I put menu link outside the root is I want to menu be visible before page loaded and react start running. So I want to not refreshing page and also I want to link be outside the react root, this is my question – Ali Akbar Azizi Dec 08 '19 at 18:24
0

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

Ali Akbar Azizi
  • 3,272
  • 3
  • 25
  • 44