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.
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>`),
]}
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>
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.