Reputation: 63
I have a component that takes in a number "n", and I am trying to dynamically render an item n times, but I need to put an HTML tag inside this render. How do i get it to render the tag with its effect instead of as a string?
Example:
//variables
props.multiple = a number (for example 2)
props.base1 = a number (lets say 5)
props.exp1 = also a number (lets say 3)
const Multiple = (props) => {
let result = "";
for(let i = 0; i < (props.multiple - 1); i++){
console.log("i: "+i);
result += `${props.base1}<sup>${props.exp1}</sup> + `;
}
console.log("result: "+result);
return <span>{result}</span>;
}
I want this to render like this:
<span>
{props.base1}<sup>{props.exp1}</sup> +
{props.base1}<sup>{props.exp1}</sup> +
{props.base1}<sup>{props.exp1}</sup> +
... however many times n is equal to
</span>
looking like this on the webpage:
5^3 + 5^3 + 5^3 + ... n times
however right now my html tags are either being printed as a string or the render is just [object Object
instead of the actual values. How do i do this?
Upvotes: 0
Views: 650
Reputation: 1
The problem with your example is that you are forming a string while you should be forming React elements. Therefore, you need to build an array of elements rather than concatenating to a string:
const MyFunction = ({ multiple, base1, exp1 }) => {
const format = () => <React.Fragment>{base1}<sup>{exp1}</sup> + </React.Fragment> // or <></>, but not supported here
return (
<span>{_.times(multiple, format)}</span>
);
};
const domContainer = document.querySelector('#root');
ReactDOM.render(<MyFunction multiple={2} base1={5} exp1={3} />, domContainer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js"></script>
<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="root"></div>
As another thought I would suggest to not loop like that and append to a string, but rather use something functional like lodash as suggested in the snippet to build the array more declaratively.
Upvotes: 0
Reputation: 1534
That's true because you are appending to the results
variable all strings hence props.base1
and props.exp1
are coerced to string too.
What you probably want to do is to append JSX elements to that results
variable and then render it on the DOM, you can do that as the following:
let result = [];
for(let i = 0; i < (props.multiple - 1); i++){
console.log("i: "+i);
result.push(<>{props.base1}<sup>{props.exp1}</sup>+</>);
}
This way what are you doing is fullfilling the results
array with all JSX Elements, hence all the HTML tags will be rendered as expected. <>
and </>
refers to a React.Fragment
(ref here) because you dont want to append another JSX element to each child, like a div
.
Upvotes: 1