score:2

Accepted answer

the fact that they come through as an array is appropriate, and useful because react can optimize re-rendering if the order of the list changes based on the key attribute. it's the fact they're in an array that makes react look for a key.

if you don't want them to be a list, per se, you could use a fragment instead:

const mycomponents = <>
  <div>component 1</div>
  <div>component 2</div>
  <div>component 3</div>
</>;

that will still come through as a single entry in props.children, but that entry will be a fragment, not an array, and react won't require keys on it, etc.

the only other answers i can think of are to put your other components in an array as well (but that will require they have a key):

const app = () => (
  <mylayoutcomponent>
    {[...components, <div key="other">some other component</div>]}
  </mylayoutcomponent>
);

const components = [
  <div>component 1</div>,
  <div>component 2</div>,
  <div>component 3</div>,
];

const mylayoutcomponent = ({ children }) => {
  console.log('✅ current child count', children.length);
  console.log('✅ expected child count', children.flat().length);
  return <div>{children}</div>
}

const app = () => (
  <mylayoutcomponent>
    {[...components, <div key="other">some other component</div>]}
  </mylayoutcomponent>
);

reactdom.render(<app />, document.getelementbyid("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>

or to ditch jsx for this one case and write the createelement call directly:

const app = () => react.createelement(
  mylayoutcomponent,
  {
    children: [
      ...components,
      <div>some other component</div>
    ]
  }
);

const components = [
  <div>component 1</div>,
  <div>component 2</div>,
  <div>component 3</div>,
];

const mylayoutcomponent = ({ children }) => {
  console.log('✅ current child count', children.length);
  console.log('✅ expected child count', children.flat().length);
  return <div>{children}</div>
}

const app = () => react.createelement(
  mylayoutcomponent,
  {
    children: [
      ...components,
      <div>some other component</div>
    ]
  }
);

reactdom.render(<app />, document.getelementbyid("root"));
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.0.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.0.0/umd/react-dom.production.min.js"></script>

i can't think of a jsx way to do that.

score:2

try concat() method.

const app = () => (
  <mylayoutcomponent>
    {components.concat(<div>some other component</div>)}
  </mylayoutcomponent>
);

it will concat your array with other component.

enter image description here


Related Query

More Query from same tag