1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00

Create example of activeClassLink using withRouter (#3188)

This commit is contained in:
Remy Sharp 2017-10-30 14:24:31 +00:00 committed by Tim Neutkens
parent 72827d25cb
commit 4c18678d54
6 changed files with 110 additions and 0 deletions

View file

@ -0,0 +1,29 @@
[![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`.

View file

@ -0,0 +1,18 @@
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);

View file

@ -0,0 +1,31 @@
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>
);

View file

@ -0,0 +1,16 @@
{
"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"
}

View file

@ -0,0 +1,8 @@
import Nav from '../components/Nav';
export default () => (
<div>
<Nav />
<p>Hello, I'm About.js</p>
</div>
);

View file

@ -0,0 +1,8 @@
import Nav from '../components/Nav';
export default () => (
<div>
<Nav />
<p>Hello, I'm the home page</p>
</div>
);