Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using anchor tags in react-router 4

I want the page to scroll down to my anchor tags when a user navigates to it through an anchor link.

I'm using react-router 4 and I've defined things as follows:

navbar:

export default (props) => {   const {      updateModal,     updateRoute,   } = props   return(     <Navbar fluid collapseOnSelect>       <Nav>         <NavDropdown eventKey="4" title="Solutions" id="nav-dropdown" noCaret>           <MenuItem eventKey="4.1">              <Link to='/solution#ipos'>TESTING ANCHOR</Link>           </MenuItem> ... 

some route:

export default class extends Component {   constructor() {     super()     this.state = {       isLoading: true     }   }   render() {     return (       <Grid className='solutions' fluid>        <Row className='someClass'>         <div>           <h2><a href='ipos' id='ipos'>Ipos morna santos paros</a></h2>           ... 

I can see the hash anchor tag in the url and in my redux store when I click on the anchor link in the navebar, and it indeed navigates to the new route, but it doesn't scroll down to the tag itself.

Is it up to me to create the scroll function or how is it supposed to work exactly?

like image 341
S. Schenk Avatar asked Jan 12 '18 09:01

S. Schenk


People also ask

Can I use anchor tags in React?

In React, relative URLs should always be handled by the link tag provided by the React Router, and pure anchor tags should only be used for absolute paths. You can also think of relative URLs as in-app navigation, for example navigating to a particular route of the app and absolute paths as external links.

How do I add an anchor link in React?

To use normal anchor links with React Router, we can use the Link component. import React from "react"; import { Link } from "react-router-dom"; const Comp = () => { //... return ( <Link to={{ pathname: "/this-view-path", hash: "#faq-1" }}>Question 1</Link> ); };

Why should you use React router's link component instead of a basic a tag in React?

The component allows you to do more than the normal link element. For instance, because it's a React component you have the benefits of having a state and what not (if you want that). You can see more documentation on here.


1 Answers

To scroll down to your anchor tags, you need to install React Router Hash Link, with:

npm install --save react-router-hash-link 

then import Hash Link:

import { HashLink as Link } from 'react-router-hash-link'; 

and then use Hash Link, for example:

<Link to="/pathLink#yourAnchorTag">Your link text</Link> 

and at the destination component, for example:

<div id= "yourAnchorTag">       <p>Linked to here<p> </div> 
like image 178
Adriano Campos Avatar answered Oct 07 '22 10:10

Adriano Campos