简体   繁体   中英

How to display the text with "anchor tag", coming from json response in react?

I have the following code:

JSON Response:

{
   "url": ["http://google.com"],
   "text": ["Click <a>me</a> for help"]
}

Code:

import React, { Fragment } from 'react';

export const Print = (props) => (
  <Fragment>
    {(props.text[0].split('/n').length && props.text[0].split('/n').map(i => {
      return <p dangerouslySetInnerHTML={{ __html: i }}></p>
    })) || text[0]}
  </Fragment>
)

My Requirement :

<p> Click <a href="http://google.com">me</a> for help <p>

This should work like above. I'm unable to understand how to render json, so that dangerouslySetInnerHTML will take anchor tag from " url " in response and assign it to i in code.

The code will be in a different file. This file will be called from a different file, and JSON response will be sent to this file as prop.

This answer is only suitable for your specific case. It ignores several <a> tags and only works with clean <a> tags, not <a class="whatever"> . Also, be careful with dangerouslySetInnerHTML , it's easy to inadvertently expose your users to a cross-site scripting

const response = {
  "url": ["http://google.com", "http://example.com"],
  "text": ["Click <a>me</a> for help", "And <a>me</a> for test"]
};

export default function App() {
  const els = response.text.map((text, i) => text.replace("<a>", `<a href=${response.url[i]}>`));

  return (
    <>
      {els.map((el, i) => <p key={i} dangerouslySetInnerHTML={{ __html: el }} />)}
    </>
  );
}

Playground

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM