Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React / React Router - Treat <a> tags like <Link> tags

Tags:

html

reactjs

I am passing pre-compiled HTML to my React component through props. The original data looks something like this.

let pageData = [
   title  : 'About',
   content: '<p>Hello <strong> World!</p><a href="/contact">Contact</a>'
]

Then in the component using the dangerouslySetInnerHTML method because I'm not sure if there is anything else to use.

import React from 'react';

export default class PostText extends React.Component {
  render() {
    return (
        <div
          dangerouslySetInnerHTML={{__html: this.props.content}}
        />
      </div>
    );
  }
}

But my question is, how can I convert the <a href="/contact">Contact</a> tag to <Link to="/contact">Contact</Link>.

Even if I don't change the mark up, is there a way to to do something like, "when I click an <a> tag, treat is as <Link> tag".

like image 869
Jordan Overbye Avatar asked Jan 28 '17 06:01

Jordan Overbye


People also ask

Why to use link instead of a tag in React?

Note: Use the NavLink or Link when you need links that are routing to pages that belong to your application. For external links, a is preferrable. The anchor tag a : This is used for links outside your webpage.

Can I use a href In React?

This href attribute contains the URL or path to the destination page. It may be a relative URL or an absolute URL. 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.

Which tag can be used in React router?

Route: Route is the conditionally shown component that renders some UI when its path matches the current URL. Link: Link component is used to create links to different routes and implement navigation around the application. It works like HTML anchor tag.

How do I add a hyperlink in React?

To add the link in the menu, use the <NavLink /> component by react-router-dom . The NavLink component provides a declarative way to navigate around the application. It is similar to the Link component, except it can apply an active style to the link if it is active.


1 Answers

I think you could do something like this, intercepting links click events inside you div and navigating with router:

<div
    dangerouslySetInnerHTML={{__html: this.props.content}}
    onClick={event => this.navigate(event)}
  />
</div>

and then:

navigate (event) {
  event.preventDefault()

  if (event.target.tagName === 'A') {
    this.props.router.push(event.target.getAttribute('href'))
  }
}
like image 189
dfsq Avatar answered Sep 30 '22 07:09

dfsq