Make multiple pages in ReactJS without using react-dom-router

Viewed 2960

I am a beginner in ReactJS web development and I wanted to ask, how can I make multiple pages in ReactJS (for example if I click on a button called "About me" that it will redirect to a different part of the whole site, for example example.com/aboutme) without using react-dom-router?

I don't want to change much in the codes because I already use my App.js as the main page.

2 Answers

You should use your own router with react-router-dom to do this. I preferably use HashRouter.

(What is the difference between HashRouter and BrowserRouter in React?)

Here is a simple example for routing in App.js;

import { HashRouter as Router, Route, Switch } from 'react-router-dom';

// Components
import Homepage from './components/Homepage';
import AboutMe from './components/AboutMe';
import Error404 from './components/Error404';

export default function App() {
    return (
        <Router>
            <Switch>
                <Route key="homepage" exact path={['/', '/homepage']}>
                    <Homepage />
                </Route>

                <Route key="aboutme" exact path="/aboutme">
                    <AboutMe />
                </Route>

                <Route path="*">
                    <Error404 />
                </Route>
            </Switch>
        </Router>
    );
}

After that when you go /aboutme you will see AboutMe component or when you go / or /homepage you will see Homepage component. If you try to go /blabla like this you will see Error404 component.

For example in your render:

<div>
    <ul>
        <li onClick={this.onItemClick}>About me</li>
    </ul>
</div>

Function that starts on click:

onItemClick: function () {
  this.props.history.push("/about-me");  
}
Related