How to Create New Page in React Js

Intro to React Router for Beginners (Multiple Page Apps)

Islem Maboud

Video Tutorial

Getting Started

React is a great front-end framework for building user interfaces with a manageable state and reusable components across your application it is widely used for building single page apps but in some cases you will need to deal with a multi-page app only running on the browser without linking with a backend-server, like a static documentation website or your portfolio where you need to have multiple pages (Home, CV, About, Contact…).

So here where it comes to the power of using react-router the React component that allows you to have declarative routing inside your React Application without needing a server or sending HTTP Requests and reloading the webpage, this how applications (not the only way) smooth animation and transitions when you move from one page to another on a website.

When working with React Router your web pages are components and when you request a specific webpage react-router compares the path you provided (Page URL) and according to that it decides to which component to render (page) so will still have the same awesome component and cool features from the part of React even when hooking it with React Router.

For this tutorial, I assume you already know how to work with React and how to setup a basic project in React either through a manual Webpack configuration or using the help of create-react-app which I'm using in this tutorial.

Now let's install react-router on our project.

          npm install react-router-dom --save        

Here we are installing the Browser version of React Router there are other versions (for React Native) and the package for The Core of react-router.

Since we are going to create a multi-page app using the help of react-router for allowing the user to navigate between these pages, so under the src/ folder create a pages folder for putting all of you app pages in there.

          src/
--pages/
--App.js
--index.js

Note that the above structure of the app is automatically created by create-react-app so if you are using then you can easily follow up.

Simple Routing

Let's try to create and initialize the structure of our application that uses the react router.

          /*App.js*/
import React, { Component } from "react";
import "./App.css";
//Import all needed Component for this tutorial
import {
BrowserRouter as Router,
Route,
Switch,
Link,
Redirect
} from "react-router-dom";

class App extends Component {
render() {
return (
<Router>
{/*All our Routes goes here!*/}
<Route path="/" component={} />
</Router>
);
}
}

export default App;

All of your Routes have to be wrapped with a Router root component where this component accepts only one single child so if you are trying to render something alongside your routes it will give you an error.

Now, let's add our home page but first, we need to create the Home page that is going to be rendered once the root path "/" has been hit.

So create an index.jsx file inside the pages/ folder.

          /*index.jsx*/
import React from "react";
//Functional Component
const MainPage = () => {
return (
<div>
<h3>Welcome to the React Router Tutorial</h3>
<small>Main Page</small>
</div>
);
};

export default MainPage;

And make sure to import your page(s) and specify their components on the route component prop.

          /*App.js*/
...
//Pages
import MainPage from "./pages"; ///< index.jsx will be automatically imported
//And render that route with the MainPage component for the root path /
...
render() {
return (
<Router>
<Route exact path="/" component={MainPage} />
</Router>
);
}
...

Start you react application, then open up your browser if everything is setup fine you should be able to see your MainPage component getting renderer without problems, but there is nothing changed!

Add Users Page

Now its time to see the real capabilities of react-router, let's try to add a new page for seeing the available users.

          /*users.jsx*/
import React from "react";
/* We simply can use an array and loop and print each user */
const UsersPage = () => {
return (
<div>
<ul>
{["Alex", "John", "Jaz", "fedrik", "missali"].map((user, idx) => {
return <li key={idx}>{user}</li>;
})}
</ul>
</div>
);
};

export default UsersPage;

Add a new route and attach it with UsersPage component.

          /*App.js*/
...
import UsersPage from "./pages/users";
...
render() {
return (
<Router>
<Route exact path="/" component={MainPage} />
<Route exact path="/users" component={UsersPage} />
</Router>
);
}

Save, Reload and navigate to /users in your browser now you should see a different web page gets renderer instead of the home page and you will see the list of the available users we put in the UsersPage Component, congrats now you have a single page application.

Link Web Pages

One of the important things to know is how to link web pages together so clients can navigate through your web pages very easily (Not all people understand how websites work!).

Linking is more like using hyperlinks (a tag) for ex: to redirect a user to a specific webpage outside of your application but to take him to an inner route of your app you have to use the Link component provided by react-router.

Let's add a link to go users page (/users) from the home page.

          //You have to use the link component to link between you pages            
import { Link } from "react-router-dom";

const MainPage = () => {
return (
<div>
<h3>Welcome to the React Router Tutorial</h3>
<small>Main Page</small>
<Link to="/users">Show List of Users</Link>
</div>
);
};

The Link component takes a (to) prop to know to which page to redirect when the user clicks the text provided, one the Link component is renderer you can notice that it uses an (a tag) to render your link.

So, if you are gonna click "Show List of Users" it will redirect you to the Users page.

Notice: you can use the Link component anywhere around you different components but you have to make sure the components are being rendered as a child of the BrowserRouter (Router).

404 Not Found Page

For a website or a simple multi-page app, a 404 page not found is one of the obvious things to handle and know how to use if you decide to work with react-router.

For a 404 page to work properly you need to wrap your routes but not outside the Router component with a Switch component that will handle a redirect from route to another and 404 pages.

Also, you should create a NotFound component that gets rendered on the 404-page error.

          /*App.js*/
import NotFoundPage from "./pages/404";
...
render() {
return (
<Router>
<Switch>
<Route exact path="/" component={MainPage} />
<Route exact component={NotFoundPage}
</Switch>
</Router>
);
}
...

Here we create a new route for the NotFoundPage component but notice this route doesn't have a path prop, in this case it will be always renderer but only if the above routes doesn't match their path there for we added an exact prop for the Routes so it will tell if either to match the exact provided path (ex: /users) or the Switch component will try the component that comes after it till it reaches the 404 page component which it has no provided path so it gets rendered without checking.

Notice that you have to keep the 404 routes last because it gets applied without checking.

The above trick for rendering a 404 page when no path is matched, but the router won't redirect to a /404 URL instead it will still display the not found path the user inputted but renders the NotFoundPage component. this is completely fine in some case but most of the time you want from the user to get redirected to a proper /404 URL when the path is not valid.

In this case, you can use the redirect Trick and create a specific path for 404 pages.

          /*App.js*/
import NotFoundPage from "./pages/404";
...
render() {
return (
<Router>
<Switch>
<Route exact path="/" component={MainPage} />
<Route exact path="/users" component={UsersPage} />
<Route exact path="/404" component={NotFoundPage} />
<Redirect to="/404" />
</Switch>
</Router>
);
}
...

You can use the Redirect component which takes a to prop as a path for redirection and it works the same as the above method but this one will indeed redirect the user into a new path instead of leaving him on his inputted invalid path.

What's Next

This tutorial was just an introduction to the React Router and how it works with some basic examples, Visit their official webpage to see more examples and all the available API Docs.

How to Create New Page in React Js

Source: https://medium.com/@ipenywis/intro-to-react-router-for-beginners-multiple-page-apps-461f4729bd3f

0 Response to "How to Create New Page in React Js"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel