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:
Summary steps:
- Let's make first some cleanup: remove hello.tsx and nameEdit.tsx
- Let's create two components PageA and PageB
- 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 to PageB.
- Let's define a navigation from PageB to PageA.
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:
import * as React from "react" export const PageA = () => { return ( <div> <h2>Hello from page A</h2> </div> ) }
-
Let's create a component called PageB as src/pageB.tsx:
import * as React from "react" export const PageB = () => { return ( <div> <h2>Hello from page B</h2> </div> ) }
-
Let's install the dependencies react-router and typescript definitions for this.
npm install react-router-dom --save npm install @types/react-router-dom --save
-
Let's define the routing in main.tsx:
import * as React from 'react'; import * as ReactDOM from 'react-dom'; import {Router, Route, HashRouter} from 'react-router-dom'; import {createHashHistory} from 'history'; import {PageA} from './pageA'; import {PageB} from './pageB';
const history = createHashHistory();
ReactDOM.render(
, document.getElementById('root') );
- It's time to check that we are following the right track:
npm start
- Let's define a navigation from PageA to PageB (_src/pageA.tsx_).
```jsx
import * as React from "react"
import {Link} from 'react-router';
export const PageA = () => {
return (
<div>
<h2>Hello from page A</h2>
<br/>
<Link to="/pageB">Navigate to Page B</Link>
</div>
)
}
-
Let's define a navigation from PageB to PageA (pageA.tsx)
import * as React from "react" import {Link} from 'react-router'; export const PageB = () => { return ( <div> <h2>Hello from page B</h2> <br/> <Link to="/pageA">Navigate to Page B</Link> </div> ) }
-
Let's run the app and check that the navigation links are working
npm start