Search code examples
javascriptreactjsstringstring-concatenation

Concatenate a String and <a href=""></a>


I'm using ReactJS and I would like to have a string and then a link as below

const example = "Hello I'm a string" + <a href="/link">And this is a link</a>

At the moment I keep getting Hello I'm a string [object Object]

How do I get the text and the link to concatenate correctly?


Solution

  • If you really need to do that, you'd use a React Fragment (or any wrapper element, like a span), like this:

    const example = <>Hello I'm a string<a href="/link">And this is a link</a></>;
    

    Or with the older more verbose syntax:

    const example = <React.Fragment>Hello I'm a string<a href="/link">And this is a link</a></React.Fragment>;
    

    Later where you want to use that within another component, you'd use a JSX expression, for instance:

    return <div>{example}</div>;
    

    Live Example:

    // The Stack Snippets version of Babel is too old
    // for <>...</> syntax.
    function Example() {
        const example = <React.Fragment>Hello I'm a string<a href="/link">And this is a link</a></React.Fragment>;
    
        return <div>{example}</div>;
    }
    
    ReactDOM.render(<Example/>, document.getElementById("root"));
    <div id="root"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>

    But normally it's not necessary, you compose things when building your render tree (a class component's render method return value, or a functional component's return value). For instance:

    function Example() {
        const msg = "Hello I'm a string";
        const link = <a href="/link">And this is a link</a>;
    
        // Composing them
        return <div>{msg}{link}</div>;
    }
    

    Live Example:

    function Example() {
        const msg = "Hello I'm a string";
        const link = <a href="/link">And this is a link</a>;
    
        // Composing them
        return <div>{msg}{link}</div>;
    }
    
    ReactDOM.render(<Example/>, document.getElementById("root"));
    <div id="root"></div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.0/umd/react-dom.production.min.js"></script>