ReactJS How do you switch between pages in React?

I'd recommend you to check react-router to solve this situation

It easily allows you to create custom routes like this:

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

const BasicExample = () => (
  <Router>
    <div>
      <ul>
        <li>
          <Link to="/">Home</Link>
        </li>
        <li>
          <Link to="/about">About</Link>
        </li>
        <li>
          <Link to="/topics">Topics</Link>
        </li>
      </ul>

      <hr />

      <Route exact path="/" component={Home} />
      <Route path="/about" component={About} />
      <Route path="/topics" component={Topics} />
    </div>
  </Router>
);

const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
);

const About = () => (
  <div>
    <h2>About</h2>
  </div>
);

const Topics = ({ match }) => (
  <div>
    <h2>Topics</h2>
    <ul>
      <li>
        <Link to={`${match.url}/rendering`}>Rendering with React</Link>
      </li>
      <li>
        <Link to={`${match.url}/components`}>Components</Link>
      </li>
      <li>
        <Link to={`${match.url}/props-v-state`}>Props v. State</Link>
      </li>
    </ul>

    <Route path={`${match.url}/:topicId`} component={Topic} />
    <Route
      exact
      path={match.url}
      render={() => <h3>Please select a topic.</h3>}
    />
  </div>
);

const Topic = ({ match }) => (
  <div>
    <h3>{match.params.topicId}</h3>
  </div>
);

export default BasicExample;

For the documentation and other examples, like nested Routing, checkout this page.


This example uses React Router v6.

file App.js

import React from "react";
import {
 BrowserRouter as Router,
 Routes,
 Route
} from "react-router-dom";
import Products from "./pages"
import Product from "./pages/product"

const App = () => {
  return (
    <Router>
      <Routes>
        <Route path="/" element={<Products />} />
        <Route path="product" element={<Product />} />
      </Routes>
    </Router>
  );
}

export default App;

file pages/index.js

import React from "react";
import {Link} from "react-router-dom";
const Products = () => {
  return (
    <div>
      <h3>Products</h3>
      <Link to="/product" >Go to product</Link>
    </div>
  );
};
export default Products;

file pages/product.js

import React from "react";
const Product = () => {
  return (
    <div>
      <h3>Product !!!!!!</h3>
    </div>
  );
}
export default Product;