fruxz
fruxz

Reputation: 23

React - how to render HTML contained into a variable?

I am trying to create a dynamic link Component that transforms a string in a string with a html anchor.

What I want to obtain is a component that returns this output:

<p>Do you want <a href="http://google.com">to search</a>?</p>

I am passing this object to the component

let phrase = {
  text :  'Do you want to search?'
  linktext : 'to search',
  linkurl  : 'http://google.com'
}

This is the component I tried but do not work and the html is rendered as a text

function InfoLink(props) {
  const q = props.phrase;
  const link = "<a href={q.linkurl} >{q.linktext}</a>";
  const text = q.text.replace(q.linktext, link);
  return (
    <p>{text}</p>
  );
}

Is there a way to have a html output from the component by using replace?

Upvotes: 0

Views: 792

Answers (3)

FaSh
FaSh

Reputation: 119

The variable link is a JSX Object and you are adding it to an string. So the result will be something like: Do you want [Object][Object]. To solve this problem, you should split the string you want to show and the object and return both.

export default function App (props){
const q = props.phrase;
const link = <a href={q.linkurl}>{q.linktext}</a>;
const text = q.text.split(q.linktext)[0];
return (
    <p>{text}{link}</p>
);}

Hope this can help.

Upvotes: 0

You can split your sentence in 3 parts:

text_before_link <a href={q.linkurl}> text_with_link </a> text_after_link

Where...

text_before_link = q.text.substr(0,q.text.indexOf(q.linktext));
text_with_link = q.linktext;
text_after_link = q.text.substr(q.text.indexOf(q.linktext)+q.linktext.length);

Something like that.

Upvotes: 0

KevBot
KevBot

Reputation: 18908

You can split the text, and output the split text along with a react component for the anchor:

let phrase = {
  text :  'Do you want to search?',
  linktext : 'to search',
  linkurl  : 'http://google.com'
}

function InfoLink(props) {
  const q = props.phrase;
  const link = <a href={q.linkurl}>{q.linktext}</a>;
  const [part1, part2] = q.text.split(q.linktext);
  return (
    <p>{part1}{link}{part2}</p>
  );
}

ReactDOM.render(<InfoLink phrase={phrase}/>, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

Upvotes: 1

Related Questions