Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
97
rated 0 times [  102] [ 5]  / answers: 1 / hits: 66669  / 8 Years ago, mon, november 7, 2016, 12:00:00

Frustrating times in React world... I need to be able to create markup based on certain criterias. For example, I receive an array of items. I need to check these items, and based on criteria, I need to generate different markup. So for example, I have a function that receives an array of items:



processItems(itemArray) {
// Create an empty array that will hold the final JSX output.
let buffer = []

// Somehow push the first required markup into the buffer.
buffer.push(<div classNamecontainer flex center>);

// ... here we do a switch statement that evaluates each item in the 'itemArray' argument and based on that I create different <div className=XYZ>{...put stuff here...}</div> markup, which I will push into the buffer - which will contain the final JSX output...

// Now I close the initial container element
buffer.push(</div>);

// And return the buffer for display inside the render() function
return buffer;
}


The problem is, I cannot simply do array.push() to add individual markups into an array because react doesn't like it for some reason, and I will just end up with gibberish stuff that gets display.



Any ideas how could I possibly do this?


More From » reactjs

 Answers
36

Your solution should look like this:



processItems(itemArray) {
// Create an empty array that will hold the final JSX output.
let buffer = []

buffer.push(<div>A</div>);
buffer.push(<div>B</div>);
buffer.push(<div>C</div>);


// And return the buffer for display inside the render() function
return (
<div classNamecontainer flex center>
{buffer}
</div>
);
}


JSX is not HTML and you cannot assemble the html elements in multiple steps.


[#60150] Friday, November 4, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karivictoriab

Total Points: 530
Total Questions: 90
Total Answers: 95

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;