Commit 4c18678d authored by Remy Sharp's avatar Remy Sharp Committed by Tim Neutkens

Create example of activeClassLink using withRouter (#3188)

parent 72827d25
[![Deploy to now](https://deploy.now.sh/static/button.svg)](https://deploy.now.sh/?repo=https://github.com/zeit/next.js/tree/master/examples/active-class-name)
# activeClassName example
## How to use
Download the example [or clone the repo](https://github.com/zeit/next.js):
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/master | tar -xz --strip=2 next.js-master/examples/active-class-name
cd active-class-name
```
Install it and run:
```bash
npm install
npm run dev
```
Deploy it to the cloud with [now](https://zeit.co/now) ([download](https://zeit.co/download))
```bash
now
```
## The idea behind the example
ReactRouter has a convenience property on the `Link` element to allow an author to set the _active_ className on a link. This example replicates that functionality using Next's own `Link`.
import { withRouter } from 'next/router';
import Link from 'next/link';
import React, { Children } from 'react';
const ActiveLink = ({ router, children, ...props }) => {
const child = Children.only(children);
let className = child.props.className || '';
if (router.pathname === props.href && props.activeClassName) {
className = `${className} ${props.activeClassName}`.trim();
}
delete props.activeClassName;
return <Link {...props}>{React.cloneElement(child, { className })}</Link>;
};
export default withRouter(ActiveLink);
import Link from './Link';
import Head from 'next/head';
export default () => (
<nav>
<style jsx>{`
.active:after {
content: ' (current page)';
}
.nav-link {
text-decoration: none;
padding: 10px;
display: block;
}
`}</style>
<ul>
<li>
<Link activeClassName="active" href="/">
<a className="nav-link home-link">Home</a>
</Link>
</li>
<li>
<Link activeClassName="active" href="/about">
<a className="nav-link">About</a>
</Link>
</li>
</ul>
</nav>
);
{
"name": "active-class-name",
"version": "1.0.0",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"author": "Remy Sharp <remy@leftlogic.com>",
"dependencies": {
"next": "latest",
"react": "^16.0.0",
"react-dom": "^16.0.0"
},
"license": "ISC"
}
import Nav from '../components/Nav';
export default () => (
<div>
<Nav />
<p>Hello, I'm About.js</p>
</div>
);
import Nav from '../components/Nav';
export default () => (
<div>
<Nav />
<p>Hello, I'm the home page</p>
</div>
);
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment