Reputation: 1580
I'm new to react.js and JavaScript. I've to pass two phone numbers in href tag -
phoneListHTML={[
"<a href='tel:{phoneNumber}'>{phoneNumber}</a>".replace('{phoneNumber}', support.expPhone),
"<a href='tel:{phoneNumber}'>{phoneNumber}</a>".replace('{phoneNumber}', support.expPhoneInternational),
]}
The "hyperlink text" is not getting replaced but actual "hyperlink clickthrough text" is replaced.
Upvotes: 1
Views: 3032
Reputation: 63524
Ideally you shouldn't be passing down raw HTML like that. You should be passing down objects/arrays containing data and allow your components to render the HTML based on that data.
// Support information
const support = { phone: '123', international: '+44 123' };
// Render the App component
// passing in the support object as props
ReactDOM.render(
<App support={support} />,
document.getElementById('container')
);
// App accepts props and returns some JSX
// which contains the Support component
// with the support object passed to it in its props
function App(props) {
return (
<main>
<h3>Support</h3>
<Support support={props.support} />
</main>
)
}
// Returns JSX with the completed information
function Support({ support }) {
const { phone, international } = support;
return (
<div>
<a href={phone}>{phone}</a><br/>
<a href={international}>{international}</a>
</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="container"></div>
Upvotes: 1
Reputation: 195972
Use a regular expression instead which allows for global replace (all occurrences) with the g
flag.
SO
phoneListHTML={[
"<a href='tel:{phoneNumber}'>{phoneNumber}</a>".replace(/{phoneNumber}/g, support.expPhone),
"<a href='tel:{phoneNumber}'>{phoneNumber}</a>".replace(/{phoneNumber}/g, support.expPhoneInternational),
]}
alternatively you could use template literals
phoneListHTML={[
`<a href="tel:${support.expPhone}">${support.expPhone}</a>`),
`<a href="tel:${support.expPhoneInternational}">${support.expPhoneInternational}</a>`),
]}
Upvotes: 2