React router allows you to use multiple pages in your web app. Usually in react, the react-router doesn't refreshes the page instead just changes the page.
Step 1:
Install react router:
npm i --save react-router-dom
Step 2:
Navigate to the index.js folder and import the required components:
Step 3:
Add this routing function in index.js
Instead of rendering App component render the Routing component as below in index.js:
Voila! Now router as been added to your react project.
When you visit localhost:3000 the App component will be rendered,
if you visit localhost:3000/project the Project component will be rendered,
if you visit localhost:3000/contact then the Contact component will be rendered.
Additional steps:
Now these routes are set to their own components to be rendered. Now you can use Link in any file inside your project as follows:
The above code can be placed in your App.js or any file that needs a header or navigator to navigate to different components (or) pages.
Note: If you use <a> instead of <Link> then the page will be refreshed which was deprecated in react.
Source code for a complete router app is available at https://bitbucket.org/balayokesh/router-tutorial/src/master/
If you are looking for some keywords of advanced concepts of react-router. There are also useParams, userRouteMatch, useLocation, useHistory, Redirect which can be used for some advanced routing.
Happy coding :)
Comments
Post a Comment