close

Filter

loading table of contents...

Headless Server Developer Manual / Version 2207

Table Of Contents

14.2.4 Navigation and Routing

Now, that the app can render a whole page, the next step is to add basic navigation. For this example, the banner from the homepage will link to an article and a link in the head of the page will lead back to the homepage.

The navigation relies on the node module "react-router-dom" and needs to be installed first:

yarn add react-router-dom

Example 14.8. Installing React Router


This will offer all capabilities of react-router, but bound to DOM elements. So in the app it provides components to create links and they will change the browser location on click. But instead of reloading the page or sending this request to the server, the router identifies the changes and matches the new URL path against different patterns, which can be provided in the App.jsx via routes and that link to the components defined here. For more information on react-router see their official documentation. The App.jsx has now a route switch, a header element linking to the homepage and a switch with two routes, matching the URL without a path to the site component and with path /article/:id, where id will be the content id of the article, to the Article component, which will be added in the next section.

import { BrowserRouter, Link, Route, Switch } from "react-router-dom";
...
  return (
    <ApolloProvider client={client}>
      <BrowserRouter>
        <Link to="/">
          <header>
            <h3>Home</h3>
          </header>
        </Link>

        <Switch>
          <Route path="/" exact component={Page}/>
          <Route path="/article/:id" component={Article}/>
        </Switch>
      </BrowserRouter>
    </ApolloProvider>
  );

Example 14.9. The App.jsx rendering with routing


The banner on the homepage need links to the article detail component. Therefor the PageGridPlacement should render link elements around each placement item and add it’s id to the URL path:

import { Link } from "react-router-dom";

function PageGridPlacement(props) {
  const name = props.name;
  const items = props.items || [];
  return (
    items.length > 0 && (
      <div className={name} style={divStyle}>
        <h1>Placement: {name}</h1>
        {items.map(
          (item, index) =>
            (item.teaserTitle || item.teaserText) && (
              <div key={index} style={divStyle}>
                {item.__typename === "CMArticleImpl" && (
                  <Link to={`/article/${item.id}`}>
                    <h2>{item.teaserTitle}</h2>
                  </Link>
                )}
                <p>{item.teaserText}</p>
              </div>
            )
        )}
      </div>
    )
  );
}

Example 14.10. The PageGridPlacement.jsx rendering links around article banner


Search Results

Table Of Contents
warning

Your Internet Explorer is no longer supported.

Please use Mozilla Firefox, Google Chrome, or Microsoft Edge.