In this sample we will start using React-Router (SPA navigation).
In this case we will provide a default userName
but let the user update it.
We will take a startup point sample 03 State:
- Let's make first some cleanup: remove hello.tsx and nameEdit.tsx
- Let's create two components PageA.tsx and PageB.tsx
- Let's install the dependencies to react-router-dom and typescript definitions for this.
- Let's define the routing.
- Let's define a navigation from PageA.tsx to PageB.tsx.
- Let's define a navigation from PageB.tsx to PageA.tsx.
Install Node.js and npm (v6.6.0 or newer) if they are not already installed on your computer.
Verify that you are running at least node v6.x.x and npm 3.x.x by running
node -v
andnpm -v
in a terminal/console window. Older versions may produce errors.
-
Copy the content from 03 State and execute:
npm install
-
Let's make some cleanup (remove src/hello.tsx and src/nameEdit.tsx files).
-
Let's create a component called PageA as src/pageA.tsx:
./src/pageA.tsx
import * as React from "react"
export const PageA = () =>
<div>
<h2>Hello from page A</h2>
</div>
- Let's create a component called PageB as src/pageB.tsx:
./src/pageB.tsx
import * as React from "react"
export const PageB = () =>
<div>
<h2>Hello from page B</h2>
</div>
- Let's install the dependencies
react-router-dom
and typescript definitions for this.
npm install react-router-dom --save
npm install @types/react-router-dom --save-dev
- Let's define the routing in main.tsx:
./src/main.tsx
import * as React from 'react';
import * as ReactDOM from 'react-dom';
- import { App } from './app';
- import { HelloComponent } from './hello';
+ import { HashRouter, Switch, Route } from 'react-router-dom';
+ import { PageA } from './pageA';
+ import { PageB } from './pageB';
ReactDOM.render(
- <App />
+ <HashRouter>
+ <Switch>
+ <Route exact={true} path="/" component={PageA} />
+ <Route path="/pageB" component={PageB} />
+ </Switch>
+ </HashRouter>,
document.getElementById('root')
);
- It's time to check that we are following the right track:
npm start
./src/pageA.tsx
import * as React from "react"
+ import { Link } from 'react-router-dom';
export const PageA = () =>
<div>
<h2>Hello from page A</h2>
+ <br />
+ <Link to="/pageB">Navigate to Page B</Link>
</div>
./src/pageB.tsx
import * as React from "react"
+ import { Link } from 'react-router-dom';
export const PageB = () =>
<div>
<h2>Hello from page B</h2>
+ <br />
+ <Link to="/">Navigate to Page A</Link>
</div>
- Let's run the app and check that the navigation links are working
npm start