Created
October 23, 2020 23:51
-
-
Save jamischarles/f3bac322c9e53693124587e0566d211e to your computer and use it in GitHub Desktop.
Examples of how to interpolate strings in React with elements (useful for i18n)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// More modern version of what's found here by Khan academy: https://github.com/martinandert/react-interpolate-component/blob/master/index.js | |
// 1) simple way to result in <div>Hello</div> | |
let a = React.createElement("div", null, "Hello"); | |
// 2) Create a fragment instead of a div so you can pass in JSX as one of the children. Key is optional I think | |
// <Fragment key="0">Hello my friend, <a href="http://www.cnn.com">This is good</a> </Fragment> | |
let b = React.createElement( | |
React.Fragment, {key: 0}, | |
"hello my friend ", | |
<a href="http://www.cnn.com">This is good</a> | |
); | |
// 3) use this option when you need to dynamically construct an element like a link inside of a string | |
// <Fragment key="0">Hello my friend, <a href="http://www.cnn.com">This is good</a> </Fragment> | |
let c = React.createElement( | |
React.Fragment, {key: 0}, | |
"hello my friend ", | |
React.createElement("a", { href: "http://www.cnn.com" }, "I am a link") | |
); | |
// you can render an array that will be concatenated like this | |
// for any tag you should use React.createElement() | |
// results in "<br/>FirstSecondThird | |
let c = [React.createElement("br"), "First", "Second", "Third"]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment