SPFx Basics: How to create a page anchor

Posted Thursday, September 13, 2018 12:14 PM by CoreyRoth

With React, sometimes the simplest of things are overly complicated.  When it comes to creating a page anchor so your users can jump down to a specific point in the page, this one is no exception.  From our old HTML4 days, you probably remember you create an anchor by doing something like the following:

 <a name="my-anchor-name"></a>

When you look for the name attribute of an anchor in React though, it's nowhere to be found.  Ultimately this has to do with React's routing system, but that doesn't really do you any good in your SPFx Web Part.  How do you get around it?  One way is to use the Link component from Fabric React.  You'll notice it does have a name attribute but using it isn't quite straight forward.  First, include Link on the page you are building.

import { Link } from 'office-ui-fabric-react/lib/Link';

Once you do that, add your Link to the page using the name attribute and a unique identifier.  This will be the destination we are jumping to.

<Link name={'my-uniqud-id'} href={'#'}></Link>

You might be wondering why I have the href tag there on the anchor tag.  That is because the Link element renders a Link element as a button instead of an anchor tag if there isn't an href tag.  You can include any value you want there, but a value is required.

Now to jump to our anchor tag, use the Link tag and include a hash tag and your unique identifier.

<Link href={'#my-unique-id'}></Link>

Again this seems like a simple topic, but if you are new to React because you just started SPFx development, this might take you a minute to figure out.

Comments

No Comments

Leave a Comment

(required) 
(required) 
(optional)
(required)