user578895
user578895

Reputation:

React: render() and multiple children

I have a map component that's out of my control that renders all of it's direct children:

<map>
  <point />
  <circle />
  <circle />
</map>

Now I'm trying to write a component that returns multiple objects:

<myComponent>
  <circle />
  <circle />
</myComponent>

And drop it into my map:

<map>
  <point />
  <circle />
  <circle />
  <myComponent>
    <circle />
    <circle />
  </myComponent>
</map>

But as the map only renders direct children, I'm not sure how to get this to work. Help?

Upvotes: 1

Views: 3020

Answers (3)

nevster
nevster

Reputation: 6465

React 16 introduced Fragments so you can do

...
render() {
  return (
  <React.Fragment>
    <circle />
    <circle />
  </React.Fragment>
  );
}
...

Upvotes: 0

Hamms
Hamms

Reputation: 5107

Simply use the special children prop:

function myComponent(props) {
  return (
    <map>
      {props.children}
    </map>
  );
}

And then use it in another component as you normally would:

...
render() {
  return (
    <myComponent>
      <circle />
      <circle />
    </myComponent>
  );
}
...

Upvotes: 2

Srikanth
Srikanth

Reputation: 461

If I am not wrong, I guess this is what you are looking for.

function MyComponent (props) {
  const objs = props.objs;
  const listItems = objs.map((obj) =>
    < {obj} />
  );
  return (
    <map>{listItems} </map>
  );
}

const objs = ['circle', 'circle'];
ReactDOM.render(
  <MyComponent objs={objs} />, //pass children i.e.,objs as props to the MyComponent
  document.getElementById('root')
);

Upvotes: 0

Related Questions