简体   繁体   中英

dangerouslySetInnerHTML and <Link>

My page requires localization. I use gettext. My i18n.__ function returns translated string and replaces %s symbols with provided arguments.

As far as I know, I can't 'dangerously set' a JSX element, however I need to insert opening and closing <Link> tags. I can't split the string into multiple pieces because back-end provides me such.

I am open to any ideas.

Here's my div element:

<div                                
    dangerouslySetInnerHTML={{ __html: i18n.__('Feel free to %scontact us%s if you have found a bug.', ['<Link to="/info">', '</Link>']) }}
/>

The solution I found is that You use an <a> tag instead of a <Link> tag and fiddle with onClick event on the whole wrapper. It goes something like this:

<div
    onClick={(e) => {
        this.navigate(e);
    }}
>
    ...
    <div                                
        dangerouslySetInnerHTML={{ __html: i18n.__('Feel free to %scontact us%s if you have found a bug.', ['<a href="/info">', '</a>']) }}
    />
    ...
</div>

And the navigate function checks if you have clicked on the <a> tag and prevents the redirect by event.preventDefault() . Then the history is "pushed":

navigate(event) {
    const siteUrl = "https://www.test.com";
    if (event.target.tagName === 'A') {
        const href = event.target.getAttribute('href');
        if (href.indexOf('mailto:') === -1) {
            event.preventDefault();
            this.props.history.push(href.replace(siteUrl, ''));
        }
    }
}

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