Home > other >  Text in a React Fragment
Text in a React Fragment

Time:11-09

render() {
  return (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  );
}

Unlike this case, I have a whole list of Fragments which I have to return according to some situation in a for loop for conditional rendering. But For that I have to write certain String text inside < />. I tried many ways but I am unable to do so. My loop is here:

for (let i = 0; i < CONTENTS.length; i  ) {
            if (CONTENTS[i].name === props.displaySubPlayArea) {
                const name = CONTENTS[i].name;
                return <name />
            }
};

It is returning <name></name> tags instead of text that name contains. Thanks In Advance

Edited: For example

function apple() {
   return (//stuff1)
}

function banana() {
   return (//stuff2)
}

function pear() {
   return (//stuff3)
}
fruits = ['apple', 'banana', 'pear']
fruits.map((fruit) => {
     return <fruit />
})

So outputs must not be :

<apple></apple>
<banana></banana>
<pear></pear>

And outputs must be the contents there are in apple, banana and pear functional components

//stuff1
//stuff2
//stuff3

and stuff can be any amount of data

CodePudding user response:

But for that I have to write certain String text inside < />

I guess you wanted to write:

// Not <name />
return <>{name}</>

// Same
return <React.Fragment>{name}</React.Fragment>

CodePudding user response:

Think what you're after is:

{fruits.map((fruit, index) => (
    <React.Fragment key={index}>
        { fruit }
    </React.Fragment>
}

CodePudding user response:

When an element type starts with a lowercase letter, it refers to a built-in component like or and results in a string 'div' or 'span' passed to React.createElement. Types that start with a capital letter like compile to React.createElement(Foo) and correspond to a component defined or imported in your JavaScript file. for more information you can read this.

function Apple() {
  return <p>apple</p>;
}

function Banana() {
  return <p>banana</p>;
}

function Pear() {
  return <p>pear</p>;
}

function App() {
  const fruits = [Apple, Banana, Pear];
  const result = fruits.map((Fruit, index) => {
    return <Fruit key={index} />;
  });
  return <>{result}</>;
}
  • Related