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}
/>

Important terms when starting with React.

We already created our first react app using create-react-app cli. Now we’ll learn some of the core terminologies involved in react.

1.Component :- its the building block of react app, just like functions, we create components to perform some functionality. It takes the given parameters (called as props) and render UI in the browser by consuming the given parameters.

Example:- we need to display contact details of a person so we’ll create the below component which takes the props as parameter when we use this component.

a)Using class syntax to create component, 

1
2
3
4
5
6
7
Class componentName extends Component {
render(){
return(
<our plain html + props passed to component>
)}
}
export default componentname

b)Component uses the render method to return the UI component to the calling parent component.

c)Export the component and it will imported with this name and used inside calling parent component
d)Calling a component with props.

2.Props, its like parameters to components like we have arguments to a function, we use them to pass data to components.

a)How to pass data :-
b)Access the prop in the component by using this keyword (refering to the current context)

{this.props.contact.name}

c)Anything which is javascript expression in jsx is presented inside {} (curly brackets)

Note:- props refer to attributes from parent components. It represents “read-only” data that are immutable.

3.Stateless function component, incase our component just returns the UI component we can use function to create a component instead of creating a class

a)What changes we have to do? 

  • Function will take passing prop as argument
  • Returns the description UI
  • this keyword is not used in accessing the props inside function.
b)Example, we replaced the our class component with “stateless function component”
Class component:-

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class ContactList extends Component{

render(){
console.log(this.props);
return(
<ol className="contact-list">
{
this.props.contact.map(contact =>
<li key={contact.id} className="contact-list-item">
<div className="contact-avatar" style={{
backgroundImage:`url(${contact.avatarURL})`
}}/>
<div className="contact-details">
<p>{contact.name}</p>
<p>{contact.email}</p>
</div>
<button className="contact-remove">
Remove
</button>
</li>
)
}

</ol>
)
}

}

export default ContactList;


Stateless function component for above class component:-

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import React, { Component } from 'react'


function ContactList(props){
return(
<ol className="contact-list">
{
props.contact.map(contact =>
<li key={contact.id} className="contact-list-item">
<div className="contact-avatar" style={{
backgroundImage:`url(${contact.avatarURL})`
}}/>
<div className="contact-details">
<p>{contact.name}</p>
<p>{contact.email}</p>
</div>
<button className="contact-remove">
Remove
</button>
</li>
)
}

</ol>
)
}

export default ContactList;

4.State:-  represents mutable data that ultimately affects what is rendered on the UI. State is managed internally by the component itself and is meant to change over time, commonly due to user input (e.g., clicking on a button on the page).

a)To create state it should be declared inside a Class

1
2
3
4
5
6
7
8
state = {
contacts : [
{
"id": "test",
"name": "Rion flower",
}
]
}


b)How to pass state to a component

1
2
3
4
5
6
7
render() {
return (
<div>
<ContactList contact ={ this.state.contacts }/>
</div>
)
}


One of the key benefits of using State in React to build UI components: when it comes to re-rendering the page, we just have to think about updating state. We don’t have to keep track of exactly which parts of the page change each time there are updates. We don’t need to decide how we will efficiently re-render the page. React compares the previous output and new output, determines what has changed, and makes these decisions for us. This process of determining what has changed in the previous and new outputs is called Reconciliation.

Note:- In React UI is function of state, when state changes UI also changes.
More Tutorials

Up and Running with React in 10 minutes

“All great achievements require time…. Maya Angelou”
We already learned how to create our first Angular.io App in 10 minutes, this time we’ll repeat the same with React library.So lets get started.

Key terminologies in react app

Brush up :-
We already know that in React we play with Javascript and embed html inside the jsx files to create our components.

JSX is awesome, but it does need to be transpiled into regular JavaScript before reaching the browser. We typically use a transpiler like Babel . We can run Babel through a build tool, like Webpack which helps bundle all of our assets (JavaScript files, CSS, images, etc.) for web projects. 


Create React App Package:-
We are going to use this tool l to get started in building a React app, as it sets up everything we need with zero configuration.


npm install -g create-react-app

Note:- This will globally install the react app, containing the babel(for trans piling), web pack (for creating the build and hot reloading)
creating react app from CLI
create-react-app contact-app
cd contact-app
npm start

It’ll run our react app on localhost:3000

launching react cli

Modify src/App.js
This file contains the component (App) which is getting rendered in the browser. Incase we open and change this file the same will be reflected on the UI.

How is the App component rendered on the UI? If we open the “src/index.js” file it will show the binding to UI and its attached to “root” element inside the “public/index.html”.
index.js file in react

Creating our own Components:-
Components are the building blocks of react application.Thus it helps in breaking our UI into small applications that are working on DOT(do one thing) principle. Components give us the power of encapsulation ( hiding all the details).

Lets create our first component say “ContactList” inside “App” file and use it inside the App component and use it.

Lines 7-25 , shows the newly created component
Line 34, is where we have used the component
 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';


//Creating our own component
class ContactList extends Component{
//our render method
render(){
//array of contact list
const people = [
{ name : "Rion"},
{ name : "Roy" },
{ name : "Ron" }
];
return(
<ol>
{people.map((person,index) =>
<li key={index}>{person.name}</li>
)}
</ol>
)
}

}
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to ContactList App</h2>
</div>
<ContactList />
</div>
);
}
}

export default App;



Playing with Props:-
Now in above case we hard coded the values of “people” array inside the contactlist component, incase we want that each component should show different contacts so we can use props feature available in React.

a)Replace the code for const people = this.props.people  (Line 6)
b)Pass props inside the contactlist component. (Line 25 & 31)

Now we can see that we used “ContactList” component twice (line 25 & 31) inside the App component and its displaying different contacts based on the “prop” parameters.

Using react component


 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//Creating our own component 
class ContactList extends Component{
//our render method
render(){
//array of contact list
const people = this.props.people
return(
<ol>
{people.map((person,index) =>
<li key={index}>{person.name}</li>
)}
</ol>
)
}

}
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to ContactList App</h2>
</div>
<ContactList people={[
{ name : "Rion"},
{ name : "Roy" },
{ name : "Ron" }
]}
/>
<ContactList people={[
{ name : "More"},
{ name : "Mor" },
{ name : "Mori" }
]}
/>
</div>
);
}
}


With this tutorial we are up and running with React App, we learned about components, how to use them and how to pass property to a component and making them reusable.

Learn more