Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build General JavaScript Application with React Router 4

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is about how to build general JavaScript applications with React Router 4. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

React Router is a very popular library in the field of React. It relies on the request URL on the location bar and the operating history of the browser to render different page content to keep it displayed, and then synchronize your app to the page of the user interface.

The new twinkle

Recently, version 4 React Router has entered the beta release phase. The reputation has been split, and this release of React Router is a complete rewrite of the previous version, which has led to a lot of disruptive API changes.

The core idea in version 4 is "declarative composability (declarative composability)"? -- it contains the component concept that makes React so good, and applies it to routing. Every part of React Router 4 is a component of React: Router, Route, Link, and so on.

One of the developers of React Router, Ryan Florence, created a short video to introduce React Router, which has been recommended by many people:

Video: https://youtu.be/a4kqMQorcnE

How was it backstage?

The new version of React Router comes with a new web page with many practical code examples, but no examples of how to use React Router to render React-based pages on the server side.

For my recent ongoing project, the speed of a search engine-friendly website is a top priority, so do you have to render the entire page on the client side? Should we just use the approach taken by all the instances on the sample page? That's not advisable. We will use an Express server to render the React page in the background.

In its introduction video, Ryan has an App component that can get data from some API to initialize its state, using the componentDidMount lifecycle approach. However, after the asynchronous data acquisition operation is completed, the component will be updated to display the data.

But this doesn't work when you want to render the App component on the server: when you use renderToString, strings with HTML code are created synchronously after calling the component's rendering method. ComponentDidMount has never been called.

So if we use the example in the Ryan video to render the App component in the background, it will only generate a "Loading..." News.

Solution

As a proof of concept, I created a demo application that basically recreates the example of Ryan in the video, but takes server-side rendering.

The application uses GitHub API to get data about Gist code snippets:

Code presentation

You can find the source code of the demo application on Github:

Https://github.com/technology-ebay-de/universal-react-router4

In short, here's what I've done...

Server/index.js

This is the code that runs every time a HTTP request is sent to the Express server:

Const routes = ['/','/ g Accord req res]; app.get ('*', (req, res) = > {const match = routes.reduce ((acc, route) = > matchPath (req.url, route, {exact: true}) | | acc, null); if (! match) {res.status (404) .send (render ()); return } fetch ('https://api.github.com/gists'). Then (r = > r.json ()). Then (gists = > res.status (200) .send (render (()) Gists)) .catch (err = > res.status (500) .send (render ()) ); app.listen (3000, () = > console.log ('Demo app listening on port 3000'))

(note: this is just an excerpt. You can find the complete source code at GitHub.)

In line 1, Mel 4, I define a routing array for app. The * * elements of the array are the initial requests for the home page, and no Gists is selected. The second route is used to show a selected Gist.

On line 6, my Express app is told to handle any request that can be matched with an asterisk.

In line 7, I use the matchPath function from React Router to simplify the routing array; the result is a matching object with information about the routes that can be matched and any parameters that can be converted from the URL path.

In line 8 Mel 11, if there is a route that doesn't match, I render an error page that says, "Page not found (Page not found)."

The render function here is just a wrapper around React's renderToString, adding the HTML code of the underlying page that surrounds the HTML of the React component (, and so on).

In line 12 App 22, I get the data from GitHub API that can fill the App state and render the Mel component.

The most obvious is line 17, where I used the StaticRouter component to initialize the React Router. The Router component type is selected by using the server rendering solution. It will never change position, which is what we need in this scenario, because in the background, we only render once and do not react directly to the user's interaction.

Line 23 captures the error message generated during processing to render an error page.

My App component looks like this:

Export default ({gists}) = > ({gists? Gists.map (gist = > ({gist.description | |'[no description]'})): (

Loading...

) {gists & & ((g.id = match.params.gistId)} / >)} / >)})

(complete source code is available on → GitHub)

In line 1, the component receives the Gist data object as an attribute.

Line 13 renders a Sidebar component that connects to different Gist links. The SidebarItem component contains data that is rendered only if there is actual Gist data. This always happens on the server side. We use this component in both server-side and client-side rendering. If the component is rendered on the client side, we may be in the process of getting new Gist data, so we will display a "Loading... (loading)" message.

Line 15 uses a Route component from the React Router library to show the Home component when the route matches to the "/" path. Here we use an exact match, otherwise any path that begins with a slash will match.

If there is Gist data to display, on line 18, another Route component will be used to display a Gist component with details of the selected Gist.

Client/index.js

As mentioned earlier, this is a generic JavaScript application (known as "isomorphism"), meaning that the same code can be used to render both server and client pages. Here is an excerpt of the code to initialize the page on the client side:

Render ((), document.getElementById ('app'))

(complete code on → GitHub)

This is much simpler than the server code! The render function on line 1 is the render function of ReactDOM. It appends the layout rendered by my React component to the DOM node.

Line 2 uses BrowserRouter (instead of the StaticRouter I use for rendering on the server side).

In line 3, I use gist data to instantiate the App component instead of getting data through GitHub API. The gist data comes from the global variable of the browser DOM, which is put there by the back end through the tag.

Thank you for reading! This is the end of the article on "how to build general JavaScript applications with React Router 4". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report