Home > Enterprise >  JSX Style React Native Components With Children
JSX Style React Native Components With Children

Time:10-15

I've done some research on this, but all of the examples I've found are convoluted. I'm trying to boil this down to its most basic elements. I've also not found an example of the style I'm looking for. But I'm wondering if I'm able to create custom React Native components with children components in this style:

function CompositeComponent(): ReactElement {

  return (
    <CustomParentComponent>
      // ✅ I would like to add child elements in the normal XML style.
      <CustomChildComponent />
    </CustomParentComponent>
  );
}

So far, this is the only way I've found how to do child elements in custom components:


function CompositeComponent(): ReactElement {

  return (
    // ❌ I'd like to avoid creating child elements in this style, if possible.
    <CustomParentComponent childComponent={<CustomChildComponent />}>
    </CustomParentComponent>
  );
}

This is done all the time with the standard React Native components such as View and Text, but I can't seem to find any examples with custom components.

What would my CustomParentComponent definition need to look like to accomplish this?

Edit -

I've tried this:

function CustomParentComponent(child: ReactElement): ReactElement {

  return (
    <CustomParentComponent>
      {child}
    </CustomParentComponent>
  );
}

But this doesn't work when I try to add the CustomChildComponent in the JSX/XML style:

function CompositeComponent(): ReactElement {

  return (
    <CustomParentComponent>
      // ❌Error❌ Type '{ children: Element; }' is missing the following properties from type 'ReactElement<any, string | JSXElementConstructor<any>>': type, props, keyts(2739)
      <CustomChildComponent />
    </CustomParentComponent>
  );
}

CodePudding user response:

You can define your CustomParentComponent to receive the children props and then you just have to render the children.

For example, consider the below code,

const CustomParentComponent = (props) => (
  <View>
    {props.children}
  </View>
);

Now you can pass your children components to your CustomParentComponent by

<CustomParentComponent>
  <CustomChildComponent />
</CustomParentComponent>

Remember children is more of a default props in React. You can verify this by simply printing out the virtual dom tree.

  • Related