React router typescript example

Using typescript to write react-router 5

No longer advocate centralized routing! Nested routing is no longer the use of . Each route is a React component.

react-router-dom

In the web side, you only need to import this package, because it takes a lot of things from the react router.

// @types/react-router-dom/index.d.ts export < . >from 'react-router';

Then look at the common functions

HashRouter / BrowerRouter

It is understood as a routing container. The sub components wrapped in it can use their own defined routing components.

// index.tsx import React from 'react'; import ReactDOM from 'react-dom'; import < HashRouter >from 'react-router-dom'; import App from './App'; ReactDOM.render(   , document.getElementById('root') );

Route

Route component. When the route is matched, this location is rendered into the corresponding content.

  • Path needs matching path
  • component matches successfully rendered components
  • exact match or not

In this case, it will only match if the path is / home. If there is no exact attribute, then when the path is / home, both the / and / home routing components will be rendered.

Nested Route

v4 and above no longer support the way of for nested routing, but directly put the child routing component in the position that needs to be rendered in the parent component.

Читайте также:  Java open with dialog

This nested routing method needs to ensure that the parent component has the same routing prefix (/) as the child component, and that the parent component does not have the exact attribute. (the purpose is to render the parent component first, and then match the child routing components defined inside the parent component)

Dynamic routing

Like other routing plug-ins, use colons to configure dynamic routes.

/other/1 Will match /other and /other/:id These two routing components, according to the actual situation /other Routing component settings exact Attribute.

useParams Get route parameters
// @types/react-router/index.d.ts export function useParams = <>>(): < [p in keyof Params]: string >;

The useParams() method returns an object, and directly taking the property TS will prompt that the property does not exist in the empty object. According to the specification of TS, an interface can be defined in the dynamic routing component to define the parameters of routing.

// OtherDetail.tsx import React from 'react'; import < useParams >from 'react-router-dom'; interface RouteParams < id: string >export default () => < const params = useParams(); return ( //Dynamic route: ) >
props get route parameters

The props data type of routing component is RouteComponentProps

// @types/react-router/index.d.ts export interface RouteComponentProps = <>, C extends StaticContext = StaticContext, S = H.LocationState> < history: H.History; location: H.Location; match: match; staticContext?: C; >

There are many match attributes

// @types/react-router/index.d.ts export interface match = <>>

In dynamic routing / other/1, the value of props.match.url is / other/1, and the value of props.match.path is / other/:id. Getting the properties in props.match.params still tells TS which properties are available.

import React from 'react'; import < RouteComponentProps >from 'react-router-dom'; interface RouteParams < id: string >export default (props: RouteComponentProps) => < return ( //Dynamic routing: ) >
useRouteMatch get route matching information

As mentioned above, we can use props to get the information related to routing, including match, params, etc. we can use props.match to get the matching information of routing. You can also use the useRouteMatch method.

// @types/react-router/index.d.ts export function useRouteMatch = <>>( path?: string | string[] | RouteProps, ): match | null;

Note that the return value of useRouteMatch() may be null and cannot be accessed simply in the form of match. *.

// Other.tsx import React from 'react'; import < useRouteMatch >from 'react-router'; export default () => < const match = useRouteMatch(); return ( Routing path: ) >

useLocation and useHistory are used similarly.

Switch

Switch matches only the first routing component in the subcomponent. As mentioned earlier, without setting the exact property, / home will match / and / home routing components at the same time. Using switch can make a single match, but it is also related to the placement order.

The component encapsulating the < a >label performs route jump.

Similar to the use of Link, the active class name will be added by default to the component whose current routing path matches the to property.

to home to other to other/1

When you click the to other/1 link, the to other link will also be added with the active class name, which is similar to the Router component, so for such navigation, you usually need to add the exact attribute.

Redirect

The to property is used for redirection, which is usually used in Switch as the processing of matching failure.

Programming route

The history object returned by useHistory() calls the push method.

Parameter passing

params

// Routing component /> // Home.tsx interface RouteParams < id: string >export default () => < const params = useParams(); return ( 
) > // Link jump to home // history jump import < useHistory >from 'react-router-dom'; export default () => < const history = useHistory(); const pushRouteParams = () =>< history.push('/home/1') >; return (
); >;

state

// Routing component /> // Home.tsx import < useLocation >from 'react-router-dom'; export default () => < const location = useLocation(); return ( ) > // Link jump >>>to home // history jump history.push( < pathname: '/home', state: < id: 1 >>)

query

// @types/history export interface Location

The location object has no query attribute. It should not provide this method

push and replace

// Link  // history history.push(. ) history.replace(. )

Hook function

After v4, functions such as onEnter, onUpdate, and onLeave are no longer provided. Instead, the routing components correspond to life cycle methods such as componentDidMount, componentDidUpdate, and componentWillUnmount in React, respectively. This happens to be replaced with the new feature useEffect.

Use useEffect in the routing component to control the routing permission with history.replace()

const history = useHistory(); const state = true; useEffect(() => < if (!state) < history.replace('/'); >>);

It is also written as a custom Hook, which is used in multiple routing components

function useUserRole(state: boolean) < const history = useHistory(); useEffect(() => < if (!state) < history.replace('/'); >>); > useUserRole(false);

Added by New Coder on Thu, 14 Nov 2019 11:14:41 +0200

  • Java — 6234
  • Python — 2579
  • Javascript — 2100
  • Database — 1608
  • Linux — 1477
  • Back-end — 1449
  • Front-end — 1432
  • Spring — 1358
  • Algorithm — 1311
  • Android — 1124
  • MySQL — 1040
  • C++ — 1022
  • Programming — 966
  • network — 827
  • data structure — 820
  • Attribute — 785
  • C — 721
  • github — 646
  • less — 645
  • SQL — 639

Источник

How to use React Router v6 in a React-TypeScript application

Build a “portfolio” website with React and TypeScript

Table of contents

Introduction

React Router is a widely used, popular routing library in React applications. The version 6 (v6) of React Router was recently released which has gone through some fundamental changes compared to the previous versions making it even easier to use. For instance, the new version is about 60% lighter than the previous versions and some changes in component names which are talked about in upcoming lines.

In this project we are going to have an introduction to the fundamentals of React Router v6 by building a “portfolio” website.

The focus of this article is React Router v6 and introducing its most commonly used components , therefore, creating and styling the pages will not be covered in depth. However, the source code is publicly available in my Github. Click here to get access to the source code.

While building a “Portfolio” web app the following will be covered:

For creating this application we are going to use create-react-app with TypeScript template. The reason for using TypeScript as said in its documentation is that “it can highlight unexpected behavior in your code, lowering the chance of bugs” therefore makes debugging easier for us.

Creating the react app

Go to your working directory and create a react app with a TypeScript template:

npx create-react-app your-app-name> --template typescript 

Our app is called react-router-vsix-app , change directory to the app’s folder, open your code editor (I am using VSCode) and remove the files which are not being used in the application such as logo, favicon and test files. Go to your App.tsx and remove all the code inside the return section. Your App.tsx should look like this at this stage:

import React from "react"; import "./App.css"; function App( ) < return ( div className="App">/div> ); > export default App; 

Create pages and components

Create three folders inside the src folder: components, pages and img. Create NavBar.tsx and Footer.tsx inside the components folder and Home.tsx , About.tsx , Portfolio.tsx and Contact.tsx inside the pages folder.

Install the react-router-dom

npm install react-router-dom@6 

In App.tsx wrap all the components inside the component. is a parent component and is used to store all the other components. It connects the app to the URL by using HTML5 History API so the User Interface (UI) stays in sync with the URL.

In version 6 of react router is deprecated and is not exported from react-router-dom. So we do not need to wrap a specific route by . However, we use instead. Routes wrap which takes a prop called element where we pass our components to.

Moreover, we do not need to use the exact prop anymore. The new algorithm enables us to match a specific route without using the exact prop. All these changes make the version 6 of React-Router-dom very easy to use.

Import , and from react-router dom on the top of your App.tsx file.

Define routes to each page:

import React from "react"; import < BrowserRouter, Routes, Route > from "react-router-dom"; import "./App.css"; import < About > from "./pages/About"; import < Contact > from "./pages/Contact"; import < Home > from "./pages/Home"; import < Portfolio > from "./pages/Portfolio"; function App( ) < return ( div className="App"> BrowserRouter> NavBar /> Routes> Route path="/" element=Home />> /> Route path="/about" element=About />> /> Route path="/portfolio" element=Portfolio />> /> Route path="/contact" element=Contact />> /> /Routes> Footer /> /BrowserRouter> /div> ); > export default App; 

Create the Navbar

In this project react-bootstrap is used to style and create components. Feel free to code the Navbar from scratch or use any other frameworks and libraries. Install react-bootstrap if decided to use it in your application:

npm install react-bootstrap bootstrap 

Import , and from react-bootstrap and from react-router-dom on top of your NavBar.tsx file. enables us to navigate between the pages by using the prop to .

To make the Navbar responsive we need to collapse it on small displays and toggle it back to the original state on larger ones. For this we will use and from react-bootstrap. Wrap the navigation links inside the component.

import React from "react"; import < Navbar, Container, Nav > from "react-bootstrap"; import < Link > from "react-router-dom"; export const NavBar = () => < return ( Navbar sticky="top" expand="md"> Container> Navbar.Toggle aria-controls="responsive-navbar-nav" /> Navbar.Collapse id="responsive-navbar-nav"> Nav> Link to="/">Home/Link> Link to="/about">About/Link> Link to="/portfolio">Portfolio/Link> Link to="/contact">Contact/Link> /Nav> /Navbar.Collapse> /Container> /Navbar> ); >; 

The useNavigation Hook

There are two react router interfaces being used to navigate between pages:

useNavigate replaces useHistory from the previous version of React Router and is being used to handle events. For example when we want to navigate back and forward between pages.

A back link is added to each page so the user can navigate to the previous page through a click event. To do this first import useNavigate and save it into a variable which is going to be used later in handling the click event. The minus number shows that we want to go back to the previous page (-1):

let navigate = useNavigate(); const handleBack = () => < navigate(-1); >; 

Now we can call our navigation handler function which we defined above in our components:

Button onClick= variant="link">Back/Button> 

Adding content and styling

As stated above the main focus of this tutorial was introducing the version 6 of react-router-dom and its usage with React and TypeScript. If interested in the content and styling the app the way I did, check out the source code in my GitHub . Feel free to use this template to build your portfolios.

home.png

This article was originally published on Medium.

I would love to see your portfolios, send me a message with a link to your websites either here or to my Twitter account.

Did you find this article valuable?

Support Sevda Amini-Uhde by becoming a sponsor. Any amount is appreciated!

Источник

Оцените статью