Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting html inside string variable used in React component

I have a react app I am building for my portfolio site. Currently i have the app written in JSX so i can add stuff like:

class Project extends React.Component {
render() {
    return (
        <div className={this.props.project.class}>
            <h1>{this.props.project.header}</h1>
            <div>
                <div className='description'>
                    <p>{this.props.project.description}</p>
                    <p>The Tech Stack</p>
                    <ul>
                        {
                        this.props.project.items.map(function(listValue){
                            return <li>{listValue}</li>;
                        })}
                    </ul>
                </div>
                <div className='image'>

                </div>
            </div>

        </div>
    );
}

}

to my component. I am currently managing my long strings of text in a different file called Text.js:

export let exampleText = "Graded is a application developed by <a href='google.com'> Link here. </a> and myself for our second year user interfaces course.";

And access it in my jsx file here:

var gradedItems = {
    class: "gradedSection content",
    header: "Graded",
    description: Text.exampleText,
    items : ["Java", "Android"]
}

and then it gets displayed in the <p> tags in the above component. However as I mentioned the link doesn't actually render and the html tags don't get rendered. So it looks like some text and then a tag in the website.

How should I go about adding these html tags within this string so when the component renders it, the html elements inside get rendered out?

Is it even possible in this situation, is there a better way of doing what I'm trying to achieve?

Thanks as always SO!

like image 767
ZarifS Avatar asked Dec 14 '22 19:12

ZarifS


1 Answers

You just need to use dangerouslySetInnerHTML and it will help.

Example usage:

let exampleText = "Graded is a application developed by <a href='google.com'> Link here. </a> and myself for our second year user interfaces course.";
function Component() {
  return <div dangerouslySetInnerHTML={{__html: exampleText }} />;
}
like image 155
Sergii Rudenko Avatar answered Dec 17 '22 23:12

Sergii Rudenko