Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a DOM element in JSX using string concatenation

A question from a new guy in React and JSX. There is a probably a simple answer but I can't find it anywhere :-\

I've this code:

return (<div className='link-container' >
        <a href="tel: + {this.props.item.value}">{this.props.item.value}</a>
    </div>);

The thing that is not working for me is the concatenation of the href value. Currently, the generated href value is exactly what you see, the {this.props.item.value} isn't replaced with the real value but displayed as a string. I tried many concatenation tricks but nothing seems to work. The only way I manage to make it work is to put the all href value in a different variable like this:

var hrefValue = "tel:" + this.props.item.value;
return (<div className='link-container' >
            <a href={hrefValue}>{this.props.item.value}</a>
        </div>);

This solution works but it looks a little weird to create a new variable for such a thing. Is there a simpler way to do it?

Thanks!

like image 489
Shai Avatar asked Mar 13 '23 19:03

Shai


1 Answers

Try this:

return (
    <div className='link-container' >
        <a href={"tel:" + this.props.item.value}>{this.props.item.value}</a>
    </div>);

To elaborate, the curly braces are used any time that you want to do anything other than pass a string (pass a number, pass a boolean, concatenate strings using javascript operators, etc).

like image 171
taylorc93 Avatar answered Mar 24 '23 23:03

taylorc93