-->

Working with React-Router?

“An investment in knowledge pays the best interest.” Benjamin Franklin

In our previous post we started with creating our first react app and than we learned about some basic terminologies in react. Today we are going to focus on creating the router behaviour using react library.

Incase you want to learn about filtering in react check the github code.

router example using react

Pre-requites:- 
Github for React Router


npm install --save react-router-dom
Key Terms:-

1) BrowserRouter, this component listens to changes in URL and display the correct screen on UI


  • Import Browser router in src/index.js  (Line 6 in the below code example)
  • Enclose component inside (Line 8)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
import { BrowserRouter } from 'react-router-dom'

ReactDOM.render(<BrowserRouter><App /></BrowserRouter>,
                 document.getElementById('root'));
registerServiceWorker();


2) Link, this component accepts the to property which directs the app to the given path. 

1
2
3
4
                    <Link
                        to='/create'                                        
                        >Add Contact
                    </Link>

>Contact</Link>Link component fully renders a proper anchor tag (a) with the appropriate href, you can expect it to behave how a normal link on the web behaves.

3) Route Component, this component is a critical piece of building an application with React Router because it's the component which is going to decide which components are rendered based on the current URL path.


1
2
3
 <Route path="/create"
           component={CreateContact}
    />

0 comments:

Post a Comment

Feel free to share your thoughts and experiences, to enhance Ppl learning.