Home > Back-end >  Adding link to object value in reactJS
Adding link to object value in reactJS

Time:12-29

I have this object where i put the english translation in a reactJs app, is it possible to add the url of description.href so i can make the word "here" in the description.paragraphe a link i have added it as HTML but i got the html as text

const EnMessages = {
    ra: {
        notation: {
            base: 'out of',
            read: 'Read the'
        },
        description: {
            title: 'About the book',
            paragraphe: 'The book shown were written by x, check it here',
            href: 'https://url.com/en',
        }
    }
};

description: {
    title: 'About the book',
    paragraphe: 'The book shown were written by x, check it <a href="https://url.com/en">here</a>'
}

CodePudding user response:

The way i would go about this is to seperate the paragraph into two parts like so:

description: {
    title: 'About the book',
    paragraphePart1: 'The book shown were written by x, check it ',
    paragraphePart2: 'here',
    href: 'https://url.com/en',
}

and then simply put this in my JSX:

<h3>{description.title}</h3>
<p>{description.paragraphePart1}<a href={description.href}>{description.paragraphePart2}<a/></p>

CodePudding user response:

You could put it together in the return statement, like this:

const EnMessages = {
    ra: {
        notation: {
            base: 'out of',
            read: 'Read the'
        },
        description: {
            title: 'About the book',
            paragraphe: 'The book shown were written by x',
            href: 'https://url.com/en',
        }
    }
};

const MessageComponent = (props) => {
  const { paragraphe, href } = EnMessages.ra.description;
  return (
    <div>
      {paragraphe}, check it
      <a href={href}>here</a>
    </div>
  );
};

CodePudding user response:

You need to use dangerouslySetInnerHTML to achieve that functionality

for example:

<div dangerouslySetInnerHTML={{__html: yourHTMLCodeHere }}></div>

Now you can add your code in yourHTMLCodeHere variable and use it.

But I think use dangerouslySetInnerHTML is a bad practice.

  • Related