<div id="root"></div>
:root {
  --line-size: 3px;
  --line-colour: #74c6e5;
  --hover-colour: #07698e;
}

body {
  padding: 30px;
  margin: 0;
  font-family: Helvetica, Arial, sans-serif;
}

ul, li {
  list-style: none;
  padding: 0;
  margin: 0;
}

.wrapper {
  max-width: 1000px;
  padding: 30px;
  margin: 0 auto;
}

.tab-content {
  padding: 30px 0;
  line-height: 1.6;
}

/* Tabs */
.tabs {
  display: block;
  position: relative;
}

.tabs-list {
  display: flex;
  border-bottom: var(--line-size) solid #ecf0f5;
}

.tabs-list__item {
  margin-right: 30px;
}

.tabs-list__tab {
  display: block;
  color: #2c3642;
  padding: 18px 6px;
  background: none;
  transition: background-color 600ms cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  text-decoration: none;
  font-weight: bold;
  white-space: nowrap;
}

.tabs-list__tab:after {
  content: '';
  position: absolute;
  top: 100%;
  left: 0;
  height: var(--line-size);
  width: 100%;
}

.tabs-list__tab:hover {
  color: var(--hover-colour);
}

.tabs-list__tab.active:after {
  background-color: var(--line-colour);
}

.tabs-list__tab.active.animating:after {
  background-color: transparent;
}

.tabs-list__underline {
  position: absolute;
  bottom: 0;
  left: 0;
  height: var(--line-size);
  background-color: var(--line-colour);
}
const { HashRouter, Switch, Route, Redirect, Link, matchPath, useLocation } = ReactRouterDOM;
const { AnimatePresence, motion } = Motion;

const debounce = (func, wait, immediate) => {
	var timeout;
	return function() {
		var context = this, args = arguments;
		var later = function() {
			timeout = null;
			if (!immediate) func.apply(context, args);
		};
		var callNow = immediate && !timeout;
		clearTimeout(timeout);
		timeout = setTimeout(later, wait);
		if (callNow) func.apply(context, args);
	};
};

const Underline = ({ refs, activeRoute, finishAnimating, animating }) => {
  const [{ x, width }, setAttributes] = React.useState({
    x: 0,
    width: 0,
  });

  const updateAttributes = React.useCallback(() => {
    if (refs && refs[activeRoute]) {
      setAttributes({
        x: refs[activeRoute].current.offsetLeft,
        width: refs[activeRoute].current.getBoundingClientRect().width,
      });
    }
  }, [activeRoute, refs])

  // Update attributes if active route changes (or refs change)
  React.useEffect(() => {
    updateAttributes();
  }, [activeRoute, refs, updateAttributes]);

  // After window resize, recalculate
  React.useEffect(() => {
    const recalculateAttrs = debounce(() => {
      updateAttributes();
    }, 500);

    window.addEventListener('resize', recalculateAttrs);
    return () => {
      window.removeEventListener('resize', recalculateAttrs);
    };
  });

  return (
    <motion.div
      className="tabs-list__underline"
      animate={{
        x,
        width,
      }}
      style={{
        opacity: animating ? 1 : 0,
      }}
      onAnimationComplete={finishAnimating}
    />
  );
};

const Tab = React.forwardRef(
  ({ active, item, animating, startAnimating }, ref) => (
    <li className="tabs-list__item" key={`tab-${item.route}`}>
      <Link
        to={item.route}
        className={`tabs-list__tab ${active ? 'active' : 'inactive'} ${animating ? 'animating' : ''}`}
        ref={ref}
        onClick={startAnimating}
      >
        {item.name}
      </Link>
    </li>
  ),
);

const Tabs = ({ items }) => {
  const [animating, setAnimating] = React.useState(false);

  const tabRefs = items.reduce((acc, item) => {
    acc[item.route] = React.createRef();
    return acc;
  }, {});

  const location = useLocation();

  // Find active path
  const active = items.find((item) =>
    matchPath(location.pathname, {
      path: `/${item.route}`,
      exact: true,
    }),
  );

  const activeRoute = active && active.route;

  return (
    <React.Fragment>
      <div className="tabs">
        <ul role="tablist" aria-orientation="horizontal" className="tabs-list">
          {items.map((item) => (
            <Tab
              key={item.route}
              location={location}
              item={item}
              ref={tabRefs[item.route]}
              active={activeRoute === item.route}
              animating={animating}
              startAnimating={() => setAnimating(true)}
            />
          ))}
        </ul>
        <Underline
          refs={tabRefs}
          activeRoute={activeRoute}
          finishAnimating={() => setAnimating(false)}
          animating={animating}
        />
      </div>
      <AnimatePresence exitBeforeEnter>
        <Switch location={location} key={location.pathname}>
          {items.map((item) => (
            <Route
              key={item.route}
              path={`/${item.route}`}
              render={() => (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  exit={{ opacity: 0 }}
                >
                  {item.render()}
                </motion.div>
              )}
            />
          ))}
          {/*
            Need to wrap the redirect in a motion component with an "exit" defined
            https://www.framer.com/api/motion/animate-presence/#animating-custom-components
          */}
          <Route
            key="redirection"
            render={() => (
              <motion.div exit={{ opacity: 0 }}>
                <Redirect to={items[0] ? `/${items[0].route}` : '/'} />
              </motion.div>
            )}
          />
        </Switch>
      </AnimatePresence>
    </React.Fragment>
  );
};

function App() {
  return (
    <HashRouter>
      <Tabs items={[
          {
            name: 'Tab #1',
            route: 'id1',
            render: () => (
              <div className="tab-content">
                Depths burying snare value law merciful value snare society eternal-return decieve aversion.
                Holiest virtues pious war depths noble inexpedient against endless ultimate. Merciful
                disgust convictions grandeur abstract battle gains revaluation fearful inexpedient right
                holiest faithful battle. Merciful depths decrepit intentions virtues salvation war ultimate.
                Sea transvaluation virtues suicide battle against victorious.
              </div>
            )
          },
          {
            name: 'Tab #2',
            route: 'id2',
            render: () => (
              <div className="tab-content">
                Ideal overcome free burying grandeur aversion. Dead morality self right superiority passion
                virtues hope society play of snare grandeur. Good oneself burying law good ultimate burying.
                Play justice snare holiest noble sea reason marvelous right.
              </div>
            )
          },
          {
            name: 'Tab #3',
            route: 'id3',
            render: () => (
              <div className="tab-content">
                Inexpedient gains prejudice aversion pious snare noble ocean ocean overcome self ubermensch
                prejudice philosophy. Ocean strong sea burying reason ultimate burying spirit. Pious christianity
                decieve endless abstract decrepit abstract. Ocean burying depths evil horror suicide mountains
                fearful depths christianity disgust gains horror. Self marvelous passion faith against grandeur.
              </div>
            )
          }
        ]} />
    </HashRouter>
  );
}

ReactDOM.render(<App />, document.getElementById('root'));
View Compiled
Run Pen

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

  1. https://unpkg.com/react@16.10.2/umd/react.development.js
  2. https://unpkg.com/react-dom@16.10.2/umd/react-dom.development.js
  3. https://unpkg.com/framer-motion@1.6.7/dist/framer-motion.js
  4. https://unpkg.com/react-router-dom@5.1.2/umd/react-router-dom.js