John Ketterer
John Ketterer

Reputation: 137

How can I pass down through props a string of text with a link embedded within?

I have a few sentences to pass down as a prop for a component and I would like the word "here" to include a link so the user can click.

I have tried the plus sign to concat the string, I have tried to use replace (example below) but I cannot find any solutions.

The "replace" method leaves [object Object] in place of the word here.

Example code:

const textWithoutLink= "First part of the project is on another page. For a 
full description you can go here for a full explanation and walkthrough of 
the project."

const textWithLink= textWithLink.replace('here', <a href= 
'www.page.com'>HERE</a>)

return(
    <projectcard 
         text={textWithLink}
    />
)

Upvotes: 1

Views: 830

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074028

Send it as a React fragment rather than as a string:

const fragment = <>
    First part of the project is on another page. For a full description you can go <a href="http://www.page.com">here</a> for a full explanation and walkthrough of the project.
</>;

<ProjectCard 
     text={fragment}
/>

IF for some reason that's impossible (but it really shouldn't be), you could use dangerouslySetInnerHTML in ProjectCard instead, using the string with HTML in it. But it has that name, and is awkward to use, for a reason. :-)


Note that in the above I've assumed that your component is ProjectCard, not projectcard, as the latter being in all lower case would mean React/JSX would assume it was an HTML element, not a React component.

Upvotes: 3

Related Questions