4

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Create your own router? https://ui.dev/build-your-own-react-router/ – evolutionxbox Jul 28 '21 at 18:02
  • You should create your own router to do this. You can follow the tutorial evolutionxbox mentioned. Also better aproach would be create a Component for homepage(and other pages) and use that component with router so app.js will be cleaner. – Closery Jul 28 '21 at 18:11
  • You can give this article a try https://dilshankelsen.com/react-routing-without-react-router/ – Beginner Jul 28 '21 at 18:14

2 Answers2

2

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.

Closery
  • 828
  • 9
  • 14
0

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");  
}
Daniel
  • 97
  • 10