Professional Documents
Culture Documents
Document 1
Document 1
Introduction of react.
React is a JavaScript library for building user interfaces. It was voted the most loved in the
“Frameworks, Libraries, and Other Technologies” category of Stack Overflow’s 2017 Developer
Survey.
React is a JavaScript library and React applications built on it run in the browser, NOT on the server.
Applications of this kind only communicate with the server, when necessary, which makes them
amazingly fast compared to traditional websites that force the user to wait for the server to re-
render entire pages and send them to the browser.
React is used for building user interfaces - what the user sees on their screen and interacts with to
use your web app. This interface is split up into components, instead of having one huge page you
break it up into smaller pieces known as components. In more general terms, this approach is
called Modularity.
⦁ It is declarative: React uses a declarative paradigm that makes it easier to reason about your
application.
⦁ It is efficient: React computes the minimal set of changes necessary to keep your DOM up-to-
date.
⦁ And it is flexible: React works with the libraries and frameworks that you already know.
Features of ReactJs
JSX: JSX is an extension to java script. Though it is not mandatory to use JSX in react, it is one of
the good features and easy to use.
Components: Components are like pure java script functions that help make the code easy by
splitting the logic into reusable independent code. We can use components as functions and
components as classes. Components also have a state, props which makes life easy. Inside a class,
the state of each of the props is maintained.
Virtual DOM: React creates a virtual DOM, i.e., in-memory data -structure cache. Only the final
changes of DOM have later updated in the browsers DOM.
JavaScript Expressions: JS expressions can be used in the .jsx files using curly brackets, for
example {}.
Advantages of ReactJs
⦁ ReactJS uses virtual DOM that makes use of in-memory data-structure cache, and only the
final changes are updated in browsers DOM. This makes the app faster.
⦁ You can create components of your choice by using the react component feature. The
components can be reused and helpful in code maintenance.
⦁ ReactJS has become extremely popular in a short span and maintained by Facebook and
Instagram. It is used by many famous companies like Apple, Netflix, etc.
⦁ Facebook maintains ReactJS, the library, so it is well maintained and kept updated.
⦁ ReactJS can be used to develop rich UI for both desktop and mobile apps.
⦁ Easy to debug and test as most of the coding is done in JavaScript rather than on HTML.
Disadvantages of ReactJs
⦁ Most of the code is written in JSX, i.e., HTML and CSS are part of java script, it can be
quite confusing as most other frameworks prefer keeping HTML separate from the java script
code.
Virtual DOM
React JS Virtual DOM is an in-memory representation of the DOM. DOM refers to the Document
Object Model that represents the content of XML or HTML documents as a tree structure so that
the programs can be read, accessed, and changed in the document structure, style, and content.
5. App (root component) is the main component of React and its render in root Element of the
index.html by index.js file.
6. App components contain a function which return something which look like an HTML
Template.
9. Babel convert JSX to HTML file and render into the HTML Dom.
11. For Example. In JSX instead class attribute we use class Name which is having Camel case and
when this executed its converted into class as HTML attributes.
12. In version 17, we do not need to import react. (Check your React Version)
17. Install React Dev tools Chrome Extension for Testing/Debugging React App
Prerequisites
1. Install Node.js and NPM
Navigate to the respective folder, where you want to create React app.
Type the command given below in a console to install create-React-app using NPX tool.
Type the command code. in a console to open the app in Visual Studio code.
Type the command given below in a console to launch React app in the Browser.
NPM start.
NPM install
Create by vite
NPM create vite@latest.
Cd “project Name”
NPM install
React JSX
React is a declarative, efficient, and flexible JavaScript library for building user interfaces. But
instead of using regular JavaScript, react code should be written in something called JSX.
Example: -
JSX (JavaScript Extension), is a React extension which allows writing JavaScript code that looks like
HTML. In other words, JSX is an HTML-like syntax used by React that extends ECMAScript so that
HTML-like syntax can co-exist with JavaScript/React code. The syntax is used by preprocessors (i.e.,
transpiler like babel) to transform HTML-like syntax into standard JavaScript objects that a
JavaScript engine will parse.
JSX provides you to write HTML/XML-like structures (e.g., DOM-like tree structures) in the same file
where you write JavaScript code, then preprocessor will transform these expressions into actual
JavaScript code. Just like XML/HTML, JSX tags have a tag name, attributes, and children.
Why JSX?
⦁ It is faster than normal JavaScript as it performs optimizations while translating to regular
JavaScript.
⦁ Instead of separating the markup and logic in separated files, react uses components for
this purpose. We will learn about components in detail in further articles.
function App () {
return (
<div className="App">
</div>
);
JSX Styling
React always recommends using inline styles. To set inline styles, you need to use camelCase
syntax. React automatically allows appending px after the number value on specific elements. The
following example shows how to use styling in the element.
Example
import React from "react";
const cssStyle = {
fontSize: "24px",
color: "white",
backgroundColor: "black",
padding: "10px",
width: "500px",
textAlign: "center",
borderRadius: "10px",
};
function App () {
return (
<div className="App">
</div>
);
JSX Comments
JSX allows us to use comments that begin with /* and ends with */ and wrapping them in curly
braces {} just like in the case of JSX expressions. Below example shows how to use comments in JSX.
Example
function App () {
return (
<div className="App">
</div>
);
Every React component have their own structure, methods as well as APIs. They can be reusable as
per your need. For better understanding, consider the entire UI as a tree. Here, the root is the starting
component, and each of the other pieces becomes branches, which are further divided into sub-
branches.
1. Functional Components
2. Class Components
Function Component
A function component is the simplest form of a React component. It is a simple function with a
simple syntax.
EXAMPLE:
MyComponent1.js
function MyComponent1(props) {
}
export default MyComponent1;
We have created a function called MyComponent1 that returned h1 tag as shown above. The name
of the function acts as an element, as shown below:
The Component MyComponent1 is used as an Html tag, i.e., < MyComponent1 /> and same is
exported using export.
app.js
function App () {
return (
<div className="App">
<MyComponent1 />
</div>
);
Class Component
Class components are more complex than functional components. It requires you to extend from
React. Component and create a render function which returns a React element. Here is a ReactJS
example that uses a class as a component.
MyComponent2.js
render () {
The Component MyComponent2 is used as an Html tag, i.e., < MyComponent2 /> and same is
exported using export. We can use MyComponent2 component in App.js file as follows:
App.js
The Component MyComponent2 is used as an Html tag i.e., < MyComponent2 />
React Fragment
We know that we make use of the render method inside a component whenever we want to
render something to the screen. We may render a single element or multiple elements, though
rendering multiple elements will require a ‘div’ tag around the content as the render method will
only render a single root node inside it at a time.
Example: Create a React app and edit the App.js file from the src folder as:
As we saw in the above code when we are trying to render more than one root element, we must
put the entire content inside the ‘div’ tag which is not loved by many developers. So, in React 16.2
version, Fragments were introduced, and we use them instead of the extraneous ‘div’ tag.
Shorthand Fragment: The output of the first code and the code above is the same but the main
reason for using is that it is a tiny bit faster when compared to the one with the ‘div’ tag inside it, as
we didn’t create any DOM node. Also, it takes less memory. Another shorthand also exists for the
above method in which we make use of ‘<>’ and ‘</>’ instead of the ‘React.Fragment’.
Note: The shorthand syntax does not accept key attributes in that case you have to use the
<React.Fragments> tag.
Syntax:
<>
<h2>Child-1</h2>
<p> Child-2</p>
</>;
React Props
Props are an optional input, and can be used to send data to the component. Props are a way of
making components easily and dynamically customizable. It’s important to note that props are read-
only and that a component must never modify the props passed to it. This also makes them come in
handy when you want to display fixed values.
Now that you know about props, make use of them in the components that we have just created
with a custom name appended to it.
Make changes to the code between the script tags in your App.js document to make it look like this:
function App () {
return (
<div className="App">
<MyComponent1 name="Beta-Labs" />
<MyComponent2 name="Beta-Labs" />
</div>
);
}
export default App;
Using Props with Function Components
1. An argument (props) is passed to the functional component. Recall that since a single argument
is being passed to function. Passing this argument lets the component know to expect some data to
be passed to it.
2. Within MyComponent1.jsx, the name you want rendered to the screen is passed in by specifying
{props.propValue} within the component’s tag.
3. In the h3 tag, {} are used to print the name that is added to the props object when it’s passed in
via the component’s tag. Notice that the name attribute is accessed using the dot syntax.
There is no limit to how many props can be supplied to a component. Now Make changes to the code
of MyComponent1.jsx to pass props to the class component:
Props are pieces of data passed into a child component from the parent while state is data
controlled within a component
What is State?
The state is an updatable structure that is used to contain data or information about the component.
The state in a component can change over time. The change in state over time can happen as a
response to user action or system event. A component with the state is known as stateful
components. It is the heart of the react component which determines the behavior of the component
and how it will render. They are also responsible for making a component dynamic and interactive.
});
A change in the state happens based on user-input, triggering an event, and so on. Also, react
components (with state) are rendered based on the data in the state. State holds the initial
information. So, when state changes, React gets informed and immediately re-renders the DOM –
not the whole DOM, but only the component with the updated state. This is one of the reasons
why React is fast.
And how does React get notified? You guessed it: with setState( ). The setState( ) method triggers
the re-rendering process for the updated parts. React gets informed, knows which part(s) to change,
and does it quickly without re-rendering the whole DOM.
• In summary, there are 2 important points we need to pay attention to when using state:
Another important question you might ask about state is where exactly we can use it. In the early
days, state could only be used in class components, not in functional components.
That is why functional components were also known as stateless components. However, after the
introduction of React Hooks, state can now be used both in class and functional components.
If your project is not using React Hooks, then you can only use state in class components.
Finally, let’s recap and see the main differences between props and state:
• Components receive data from outside with props, whereas they can create and manage their own
data with state
• Props are used to pass data, whereas state is for managing data
• State data can be modified by its own component, but is private (cannot be accessed from outside)
• Props can only be passed from parent component to child (unidirectional flow)
• Modifying state should happen with the setState () method
• Data from props is read-only and cannot be modified by a component that is receiving it from
outside.
We have learned so far that the React web applications are actually a collection of independent
components that run according to the interactions made with them. Each component in React has a
life cycle that you can monitor and change during its three main phases. There are three phases:
Mounting, Updating, and Unmounting. You can use life-cycle methods to run a part of code at
particular times in the process or application. You can refer to the below diagram to get a visual idea
of the life-cycle methods and their interactions in each phase.
Mounting
Mounting is the phase when the component is mounted on the DOM and then rendered on the
webpage. We call these methods in the following order when an element is being created and
inserted into the DOM:
• componentWillMount()
• render ()
• componentDidMount()
componentWillMount(): This function is called right before we mount the component on the DOM.
So, after this method executes, the component gets mounted on the DOM. It executes this method
before the first render of the React application. So, all the tasks that have to be done before the
component mounts are defined in this method.
componentDidMount(): We invoke this function right after the component is mounted on the DOM
i.e., this function gets called once after the render () function is executed for the first time. Generally,
in React applications, we do the API calls within this method.
Updating
We call the methods in this phase whenever State or Props in a component get updated. This allows
the React application to “react” to user inputs, such as clicks and pressing keys on the keyboard, and
ultimately create a responsive web user interface. These methods are called in the following order
to carry on the update of the component:
• componentWillReceiveProps()
• setState()
• shouldComponentUpdate()
• componentWillUpdate()
• render ()
• componentDidUpdate()
componentWillRecieveProps(): We call This function before a component gets its props reassigned.
setState(): This function can be called explicitly at any moment. This function is used to update the
state of a component.
shouldComponentUpdate(): This function is called before rendering a component and tells React
whether it should update the component on receiving new props or state. It takes the new Props and
new State as the arguments and returns whether or not to re-render the component by returning
either True or False.
componentWillUpdate(): This function is called once before the render () function is executed after
the update of State or Props.
render (): The component gets rendered when this function is called.
componentDidUpdate(): This function is called once after the render () function is executed after the
update of State or Props.
Unmounting
This is the last phase of the life cycle of the component where the component is unmounted from
the DOM. This phase has only one method:
componentWillUnmount(): This function is called once before we remove the component from the
page, and this marks the end of the life cycle.
Now that we are familiar with all the life-cycle methods of React components, let us now look at an
example to see how each function is implemented in the application code:
DisplayCycle.js
import React from "react";
import DisplayChild from ". /DisplayChild";
class DisplayCycle extends React.Component {
constructor(props) {
super(props);
this.state = {name: "Pankaj"};
console.log("Constructor");
}
componentWillMount() {
console.log ("componentWillMount Parent");
}
componentDidMount() {
console.log ("componentDidMount Parent");
}
shouldComponentUpdate() {
console.log ("shouldComponentUpdate parent");
return true;
}
componentWillUpdate() {
console.log("componentWillUpdate() called");
}
componentDidUpdate() {
console.log("componentDidUpdate() called");
}
componentWillUnmount() {
console.log("componentWillUnmount() called");
}
switchState = () => {
this.setState({name: "pankaj Kapoor"});
};
render () {
console.log ("render Parent");
return (
<div>
<input type="text" value={this.state.name} />
<DisplayChild firstname={this.state.name} />
<button onClick={this.switchState}>Click Me</button>
</div>
);
}
}
export default DisplayCycle;
React Hooks
Earlier on in React, components were either class components or functional components. Functional
components were Javascript functions that accepted props (data) to display and returned JSX.
Class components typically required more code but could store state variables and could use lifecycle
methods. This made class components the go-to option for making API calls, processing user input, etc.
Functional components became useful helpers for class components.
With the release of React 16.8 in 2019, React Hooks have finally become available to use in our production
applications. This allows React developers to make functional components stateful. Instead of using a
class component to hold stateful logic, we can use functional components.
React Hooks are not available in class-based components — but instead they allow you to use React
without JavaScript classes. If you prefer to use functions instead of classes (which is recommended in
JavaScript) you can simply start using Hooks without worrying about migrating your whole apps to classes.
Hooks enable you to use “class-features” In React by providing a set of built-in functions such as:
Hook State
let’s set up a component with state, the hooks way.
And now, let’s use a React hook. We’ll add in some state to the component. To do so, we’ll import the
useState hook from React at the top of the App.js file:
Then we’ll apply the useState hook at the top of the App component function, to set up state
functionality for the stuRoll:
const HookDemo = () => {
const [stuRoll, setStuRoll] = useState();
1. The argument to useState is its initial value. Therefore, with useState(), we are setting the initial
value of stuRoll to a blank value.
2. The useState method destructures your state object into an array of two values. The first one is
the current value of the variable that is being tracked in the component state. Therefore, in const
[stuRoll, setStuRoll] = useState(), stuRoll represents that current value. It becomes a constant that
can be used in the component code.
3. The second value returned from the useState function is a function itself. This function updates
the paired state variable. So setStuRoll updates the stuRoll value.
Within the App component, let’s create a helper method, called updateData. With this method, the
input element will set the stuRoll in the hook state. How?
This helper will call the new setStuRoll function and update the student Rollno.
const ReactDemo = () => {
const [stuRoll, setStuRoll] = useState(0);
setStuRoll(10);
return (
<div>
<h2>Hooks | Function Component Based</h2>
<h3>RollNo: {stuRoll}</h3>
<button onClick={updateData}>Update</button>
</div>
);
};
export default ReactDemo;
Comparison to traditional class Component state
Let’s compare the App component function above with the more traditional class component state
approach:
import React, {Component} from "react";
class StateDemo extends React.Component {
constructor () {
super ();
this.state = {
stuRoll: 0,
};
}
updateData = () => {
this.setState({ stuRoll: 10});
};
render () {
return (
<div>
<h2>State | Class Component Based </h2>
<h3>RollNo: {this.state.stuRoll}</h3>
<button onClick={this.updateData}>Update</button>
</div>
);
}
}
export default StateDemo;
Take note of the differences between this function version and the class version. It’s already much more
compact and easier to understand than the class version, yet they both do exactly the same thing. Let’s
go over the differences:
• The entire class constructor has been replaced by the useState Hook, which only consists of a
single line.
• Because the useState Hook outputs local variables, you no longer need to use this keyword to
reference your function or state variables. Honestly, this is a major pain for most JavaScript
developers, as it’s not always clear when you should use this.
• The JSX code is now cleaner as you can reference local state values without using this.state.
5. Hooks can only be called at the Top Level; it can't be called inside the loops or condition or nested
functions.
6. Hooks can only be called in the React Function or Custom Hooks, never use hooks in the regular
javascript function.
Hooks Effect
The Hooks Effect enables us to conduct collateral effects within the components function. The Hooks
Effect will not use the lifecycle methods of the components, and these methods exist in the class
components. Hooks Effect is similar to componentDidUpdate(), componentDidMount() lifecycle
methods.
In the above code, we invoke “useEffect” to inform the React to execute the “effect” method after
reddening the modifications in the DOM. As we declare the effects in a component, the effects can use
the state and props. React implements the effects after each render. Effects may also define how to do
“clean up”.
Side effects contain usual properties that every web application have to conduct, like:
· DOM Updation
· Consuming and Retrieving data from an API Server.
· Establishing Subscription
Side Effects
we categorize side effects into two types:
Effects with Cleanup: After updating the DOM, we have to clean up some effects. For example, when we
need to establish a subscription for any explicit data source, it is essential to clean up the memory to
ensure that there is no memory leak.
Effects without Cleanup: We use Effects without Cleanup in effect that does not obstruct the browser in
screen updation. Examples of Effects that do not need cleanup are Network requests, Manual DOM
mutations, etc.
React Events
In web development, events represent actions that happen in the web browser. By responding to events
with event handlers, you can create dynamic JavaScript applications that respond to any user action,
including clicking with a mouse, scrolling along a webpage, touching a touch screen, and more.
In React apps, you can use event handlers to update state data, trigger prop changes, or prevent default
browser actions. React has its own event handling system which is very similar to handling events on DOM
elements. The react event handling system is known as Synthetic Events. SyntheticEvent closely emulates
the standard browser event but provides more consistent behavior for different web browsers.
Handling events with react have some syntactic differences from handling events on DOM. These are:
3. In react, we cannot return false to prevent the default behavior. We must call preventDefault event
explicitly to prevent the default behavior. For example:
In plain HTML, to prevent the default link behavior of opening a new page, we can write:
function ActionLink() {
function handleClick(e) {
e.preventDefault();
console.log ('You had clicked a Link.');
}
return (
<a href="#" onClick={handleClick}>
Click_Me
</a>
);
}
In the above example, e is a Synthetic Event which defines according to the W3C spec.
To listen to events in React, add the onClick attribute, which is the event handler, to the target element.
This specifies the function to be executed when that element is clicked.
Binding in the render () method: One way to resolve the problem of binding is to call bind in a render
function. This is done by binding it in the render () function. This method requires calling. bind(this) in the
render () function.
Binding in the constructor () method: If binding in the render doesn’t work for you, you can bind in the
constructor. See an example below:
constructor(props) {
super(props);
this.showAlert = this.showAlert.bind(this);
The first this.showAlert refers to the showAlert method. Since this is done in the constructor, this refers
to the ShowAlert class component.
The second this.showAlert is also referring to the same showAlert() method, but we are now calling. bind
() on it.
The final this is the context we are passing to. bind (), and it refers to the ShowAlert class component.
It’s also important to note that if showAlert isn’t bound to the class instance, it won’t be able to access
this.setState because this will be undefined. This is another important reason to bind event handling
functions.
Binding in the arrow function: You can handle events in class components by binding them with the fat
arrow function. ES7 class properties enable bindings at the method definition, as shown in the example
below. By definition, an arrow function expression has a shorter syntax than a function expression and
does not have its own this, arguments, super, or new.target.
showAlert= () => {
alert ("I'm an alert");
}
You can control the submit action by adding an event handler in the onSubmit attribute:
Example
constructor(props) {
super(props);
event.preventDefault();
};
};
render () {
return (
<form onSubmit={this.mySubmitHandler}>
</form>
);
Note that we use event.preventDefault() to prevent the form from actually being submitted. Displaying
List in React
Lists are very useful when it comes to developing the UI of any website. Lists are mainly used for displaying
menus in a website, for example, the navbar menu. In regular JavaScript, we can use arrays for creating
lists. We can create lists in React in a similar manner as we do in regular JavaScript. We will see how to
do this in detail further in this article.
Using JSX we can show lists using JavaScript's built-in Array.map() method. The. map () method is often
used to take one piece of data and convert it to another. In our scenarios, we are taking data and
converting it to a piece of our view.
A Simple Example
Let's say we have a list of arrays that we want to show in a list:
});
return <ul>{newArr}</ul>;
}
This component uses Array’s built-in map function to create a new array newArr that has the same
number of elements, and where each element is the result of calling the function, you provide. The {}
brackets are used to render the array of elements.
return (
<ul>
{
arr.map((num) => {
return <li>{num}</li>;
})}
</ul>
);
}
The above is the shorthand code for write the map function. Since we are not doing anything in the
function's block body, we can also refactor it to a concise body and omit the return statement and the
curly braces for the function body:
return (
<ul>
{arr.map(num =><li>{num}</li>)}
</ul>
);
So, from the component’s point of view, we have to pass a list to a component using props and then use
this component to render the list to the DOM. We can update the above code in which we have directly
rendered the list to now a component that will accept an array as props and returns an unordered list.
<ul>
{list.map((item) => (
<li>{item}</li>
))}
</ul>
);
export default App;
You can see in the above output that the unordered list is successfully rendered to the browser, but a
warning message is logged to the console.
The above warning message says that each of the list items in our unordered list should have a unique
key. A “key” is a special string attribute you need to include when creating lists of elements in React. We
will discuss about keys in detail in further articles. For now, let’s just assign a key to each of our list items
in the above code.
Below is the example where we display the list of Objects with keys.
import "../node_modules/bootstrap/dist/css/bootstrap.css";
<tr key={index}>
<td>{user.id} </td>
<td>{user.username}</td>
<td>{user.password}</td>
</tr>
);
};
return (
<table class="table">
<thead class="thead-light">
<tr>
<th>#</th>
<th>Username</th>
<th>Password</th>
</tr>
</thead>
<tbody>{user.map(renderUser)} </tbody>
</table>
</div>
);
}
The key attribute is necessary for React to identify which items have changed, are added, or are removed.
Keys should be given to the elements inside the array to give the elements a stable identity. Since React
uses a virtual DOM and depends on the key to identifying items of a list, so in the above list example, we
provided a unique id to every list item.
React Router
As opposed to traditional multi-page applications, SPAs only maintain one HTML file, commonly
index.html. Instead of serving a different HTML file for each path, SPAs depend on client-side routing.
React Router is a popular client-side routing library.
Routing is a process in which a user is directed to different pages based on their action or request. ReactJS
Router is mainly used for developing Single Page Web Applications (SPA). React Router is used to define
multiple routes in the application. When a user types a specific URL into the browser, and if this URL path
matches any 'route' inside the router file, the user will be redirected to that particular route.
React Router uses component structure to call components, which display the appropriate information.
React router also allows the user to utilize browser functionality like the back button, and the refresh
page, all while maintaining the correct view of the application.
1. react-router: It provides the core routing components and functions for the React Router
applications.
It is not possible to install react-router directly in your application. To use react routing, first, you need to
install react-router-dom modules in your application. The below command is used to install react router
dom.
In our project, we will create four more components in the directory called Pages along with App.js, which
is already present.
Pages/Home.js
Pages/About.js
Pages/Contact.js
Pages/Navbar.js
App.js
which helps us to implement the Routing. Now, our app.js file looks like below.
BrowserRouter as Router
First, you'll need to set up your app to work with React Router. Everything that gets rendered will need
to go inside the <BrowserRouter> element, but we just rename BrowserRouter as Router only to reduce
the long name of the BrowserRouter. so, wrap your App in those first. It's the component that does all
the logic of displaying various components that you provide it with.
Switch
Next, in your App component, add the Switch element (open and closing tags). These ensure that only
one component is rendered at a time. It checks each route for a match sequentially and stops once the
first match is found.
function App () {
return (
<Router>
<div className="App">
<Navbar />
<switch>
<Home />
<About />
<Contact />
</switch>
</div>
</Router>
);
}
You notice that we put <Navbar /> component outside the switch, because we want that navbar will be
visible on each component that render.
Route
It's now time to add your <Route> tags. These are the links between the components and should be
placed inside the <Switch> tags.
To tell the <Route> tags which component to load, simply add a path attribute and the name of the
component you want to load with component attribute. The <Route> will return null in case the specified
URL doesn’t match the defined path.
function App () {
return (
<Router>
<div className="App">
<Navbar />
<switch>
<Route path="/" exact component={Home} />
<Route path="/about" exact component={About} />
<Route path="/contact" exact component={Contact} />
</switch>
</div>
</Router>
);
}
When the route matches /, the application shows the Dashboard component. When the route is changed
by clicking the “About” link to /about, the Dashboard component is removed and the About component
is inserted in the DOM.
Notice the exact attribute. Without this, path="/" would also match /about, since / is contained in the
route. However, we want ‘/’ to match only our render function, hence using ‘exact’ explicitly achieves
this.
Step 4: Adding Navigation Link
Link
Sometimes, we want to need multiple links on a single page. When we click on any of that particular Link,
it should load that page which is associated with that path without reloading the web page. To do this,
we need to import <Link> component in the Navbar.js file. The Link component is used to trigger new
routes. You import it from react-router-dom, and you can add the Link components to point at different
routes, with the to attribute. It is the equivalent of anchor tags: <a> </a>.
So now we should update Navbar.js for providing Navigation link in react application by replacing <a> tag
to <Link> Tag and 'href' to 'to' attribute.
Pages/Navbar.js
import React from "react";
import {Link} from "react-router-dom";
Pages/NotFound.js
import React from "react";
Let's add <Not Found /> component to routes configuration, using * as a value of the path parameter to
get a non-greedy matching.
It is important to remember that the 404 route needs to be declared in the very bottom of your route's
configuration, so the <Route /> is only mounted if any of the routes' path declared above are not
matched:
App.js
function App () {
return (
<Router>
<div class Name="App">
<Navbar />
<switch>