[React] Navigation

Navigation (Routing or Menus) is the basic building block of any web application. React is, in fact, a single-page application that can show different components on request.

Custom Solution -Navigation

You can create your navigation component. You can determine which object to navigate using the “pathname” property of the “window.location” object.

const Navigation = ({path, children}) => {
    return window.location.pathname === path ? 
        children : null;
}

export default Navigation;

Note that the special “props.children” property is used to pass all child elements directly to the element.

import React from 'react';

import Home from './Home';
import Page1 from './Page1';
import Page2 from './Page2';
import Navigation from 'Navigation';

const App = (props) => {
  
  return (
    <div className="ui container">
      
      <h1 className="ui header">My App</h1>

      <Navigation path="/">
        <Home />
      </Navigation>
      <Navigation path="/page1">
        <Page1 />
      </Navigation>
      <Navigation path="/page2">
        <Page2 />
      </Navigation> 
      
    </div>
  );
}

export default App;

Custom Component – Link

You can wrap <a> object in a component, which is the React way of coding.

import React from 'react';

const Link = ({href, className, children}) => {

  const onClick = (event) => {

    if (event.metaKey || event.ctrlKey) {
      return;
    }

    event.preventDefault();
    window.history.pushState({}, '', href);

    const navEvent = new PopStateEvent('popstate');
    window.dispatchEvent(navEvent);
  };

  return (
    <a href={href} className={className} 
      onClick={onClick}>
      {children}
    </a>
  );
}

export default Link;

The “Link” component can be used to create a menu.

import React from 'react';
import Link from 'Link';

const Header = (props) => {
  return (
    <div className="ui secondary pointing menu">
      <Link href="/" className="item"> 
        Home 
      </Link>
      <Link href="/page1" className="item">
        Page1
      </Link>
      <Link href="/page2" className="item">
        Page2
      </Link>
    </div>
  );
}

export default Header;

React-Router

The “React Router” package is one of the most popular options for React navigation. However, the downside of React-Router is that it has frequent breaking changes with version upgrades.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s