Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concatenate JSX elements into an array?

Tags:

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 className"container 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?

like image 851
pentool Avatar asked Nov 07 '16 22:11

pentool


People also ask

How do I concatenate a string and React component?

Use a template literal to concatenate strings and variables in React, e.g. "<a href={ https://example.com/${myPath} }". Template literals are delimited with backticks and allow us to embed variables and expressions using the dollar sign and curly braces ${expression} syntax.

Can you nest JSX elements into another JSX element?

You can nest JSX elements inside of other JSX elements, just like in HTML.

What is JSX element []?

What is JSX? JSX stands for JavaScript XML. JSX allows us to write HTML in React. JSX makes it easier to write and add HTML in React.

How do you concatenate variables in React?

Use the + operator to concatenate two string variables in React Native: const helloWorld = hello + world; Another version with a hardcoded string: const helloWorld2 = hello + 'World!


1 Answers

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 className"container flex center">             {buffer}         </div>     ); } 

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

like image 73
zerkms Avatar answered Sep 28 '22 02:09

zerkms