When a user goes to my domain www.example.com
they see my webpage I created using React. I want to use React to show them a different webpage when they go to www.example.com/anotherpage
instead.
This is the code I have in my index.js file which creates the webpage at www.example.com
,
JavaScript
x
3
1
const element = <h1>Hello, world</h1>;
2
ReactDOM.render(element, document.getElementById('root'));
3
Advertisement
Answer
There are multiple solution for this, if you are creating an SPA with create-react-app, then one of the most popular solution is by using react-router.
As shown in the example, then the basic routing is like this:
JavaScript
1
54
54
1
import React from "react";
2
import {
3
BrowserRouter as Router,
4
Switch,
5
Route,
6
Link
7
} from "react-router-dom";
8
9
export default function App() {
10
return (
11
<Router>
12
<div>
13
<nav>
14
<ul>
15
<li>
16
<Link to="/">Home</Link>
17
</li>
18
<li>
19
<Link to="/about">About</Link>
20
</li>
21
<li>
22
<Link to="/users">Users</Link>
23
</li>
24
</ul>
25
</nav>
26
27
<Switch>
28
<Route path="/about">
29
<About />
30
</Route>
31
<Route path="/users">
32
<Users />
33
</Route>
34
<Route path="/">
35
<Home />
36
</Route>
37
</Switch>
38
</div>
39
</Router>
40
);
41
}
42
43
function Home() {
44
return <h2>Route Home</h2>;
45
}
46
47
function About() {
48
return <h2>Route About</h2>;
49
}
50
51
function Users() {
52
return <h2>Route Users</h2>;
53
}
54
However if you are using another framework such as Next.js, then they have the filesystem pages where creating a page under /pages/
folder will create a new route.