React - dynamically adding a hyperlink (anchor html tag) to a string

Viewed 548

Let's say I have a string in React "x {y} z" and I would like to dynamically replace {y} with a hyperlink with target = "ylink" Both y and ylink would be dynamic e.g. there would be an object with the text to replace (y) and the target of the hyperlink (link). Is it possible to do this?

2 Answers

yes it's possible you can do as shown below

const getLink = ({href, name}) => {
    return(
      <a href={href} >{name}</a>
    )
  }

x {getLink({href: "google.com", name:"y"})} z  // your react string goes here

Try creating a custom CustomLink component. Using functional component approach:

const CustomLink = (linkTarget, displayString) => <a href={linkTarget}>{displayString}</a>;

You can additionally add properties to the anchor tag such as e.g. rel, target props (see documentation: https://www.w3schools.com/tags/tag_a.asp). Finally, you can evaluate your requested string, but I rather recommend just use JSX if you want to display it in DOM:

const requestedJSX = <div><span>x {<CustomLink linkTarget='ylink' displayString='y'/>} z</span></div>;

Span is there for whitespace retention - feel free to not use it according to your needs. If you are working with single-page app using routes and different pages / views, a good approach is to choose react-router library and build link systems using the react-router-dom readily available Link component (just import it). I have named the custom anchor tag code above different from "Link" as not to mix with the react-router import name.

Example: note that react-router approach does not work unless you fully set up react-router!

import { Link } from "react-router-dom";
const requestedContent = <div>X <Link to='ylink'>Y</Link> Z</div>;
Related