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?
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.
You can nest JSX elements inside of other JSX elements, just like in HTML.
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.
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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With