loading...
Cover image for Play With the React 🐘Router

Play With the React 🐘Router

saigowthamr profile image Sai gowtham Updated on ・2 min read

Play with the React-Router-Dom.

What is a React Router?

React Router Helps us to do routing in React apps and everything is a Component-Based in React Router.

Is it Dynamic or Static Routing?

  • Dynamic Routing.

What are the Requirements to implement the Routing in React Apps?

  • First, we need to install Package Called react-router-dom.
npm i -s react-router-dom

Let's play now.

create a routes.js file in your src directory like i shown in the below image.

In the routes.js file, we need to import the React and Routing Components.

Then we need to import the components which they need routing.

Like in above image i imported the App component and Posts Component.

Let's define a new Component with Routes.

What is the above code .....

I think it looks like very Interesting.

Link: Link component helps to define the navigation.
Route: Route Component helps to define the Routing.
exact: Please Load exactly App Component when my URL is /

Above all, we need to Wrap the Router Component.

that's it we are done with routing.

Now in your index.js, we need to add these Routes Component.

Open Your App.js file or a Component which you used in routing add console.log(this.props) to the code like in the below image.

app.js

Now run your dev server.

Have you seen anything in your Browser console?

There is an object available in our component.

who gives us this object?

The answer is React router passes the Object to our Component whenever we declare routes for that component.

For example, we defined the routes for App component and Posts Component.so that these Components are Now Aware of these Object in the Above image.

Programmatically navigate with React Router.

The Name tells the How to Navigate Programmatically it means Navigate me to the Some route whenever a program runs or some event happens.

For example when submitting a form.

I have already shown there is a history property available.

We can even be done with Other Ways But I'm showing with the help of history property.

Final Output.

Play with React Router Part-2

Happy coding...

React router beginners guide

Posted on Jun 1 '18 by:

saigowthamr profile

Sai gowtham

@saigowthamr

JavaScript developer, Blogger & Serverless

Discussion

markdown guide
 

Hey, Nice tutorial. Btw, I have a question. I've seen in many articles, there the Routes are inside a Switch . But in your tutorial you haven't used Switch. Why do we should use / shouldn't use Switch ?

 

A switch is used to switch between routes whenever the exact path is matching /while handling the 404 requests we need to wrap all our Routes with the Switch Component.

Refer Play with React Router Part-2

 

How to enable jsx highlighting for JavaScript file in vsc?

 

Install prettier to format your code for highlighting it depends on the theme you're using.