Idea: Introduction to React-Router (BrowserRouter, Route, and Link).
Background: https://blog.webdevsimplified.com/2022-07/react-router/ and https://www.youtube.com/watch?v=Ul3y1LXxzdU
In this exercise you have to create a very basic React App with routing.
Step 1 (create the initial React-App and install the react-router-dom lib)
Create a new React App: 'basic' by running 'npx create-react-app basic'
Navigate to your new project directory and install the react-router-dom library locally by running 'npm install --save react-router-dom '.
Verify that your initial project is up and running with: 'npm start'.
Step 2 (Clean the default src-folder)
Delete all files in the src-folder
Step 3 (App.js)
Create a new App.js fil in the src-folder.
Import React from 'react', create a simple App-component and make a default export of the component:
Step 4 (index.js)
Create a new index.js fil in the src-folder .
And verify that it still works:
Step 5 (Home.js)
Create a new 'landing page' to the app (Home.js in the src-folder). Add a simple component like:
Step 6 (Page2.js)
Create a second ' page' to the app (Page2.js in the src-folder). Add a simple component like:
Step 7 (Update the index.js file)
Import the BrowserRouter component from 'react-router-dom' and wrap it arround the App-component (routing will now be awailable all over in our App).
Step 8 (Update the App.js file)
Import the Route Component from 'react-router-dom' and the two components 'Home' and 'Page2'. Insert 2 Routs: path='/' for the Home-component and path='/page2' for the Page2-component:
Verify that your Routing is working:
a) Try both: 'localhost.3000' and 'localhost:3000/page2'.
b) What happens if you type: 'localhost:3000/page3' ?
c) Is the Browser history working (<- and ->) ?
In Single Page Applications (SPA) we don't use <a href='....> since it causes a brand new page (and clears the state of the App). In React Apps we are using the Link component from 'react-router-dom', it prevents the reload and the loss of the apps state.
Step 9 (Update the App.js file)
Import the Link Component from 'react-router-dom' and add 2 Link-components with links to the 'Home' and 'Page2'
Verify that your link is working (notice the url in the Browser)
Route parameter or URL parameter are a wellknown technique for passing values to a page during page-navigation, e.g '/user/1' if we wanted to view information about user #1.
In this exercise will we use Route Params to send a value to a page.
Step 10 (Update Page2.js)
Add imports of {Link} from 'react-router-dom', Page3 and Page4 (to be created in step 11-12). Add the following Link-tag for routing to Page3 and Page4
Step 11 (Page3.js)
Create a new file: Page3.js:
Step 12 (Page4.js)
Create a new file: Page4.js:
Step 13 (NotFound.js)
Create a new file: NotFound.js:
Step 14 (App.js)
Finally update App.js:
Congratulation! - Yes Route is nice and simple!
/ Henrik H