How can I create sub component in react native?

2k views Asked by At

I saw react native elements - Card component working like this.

<Card>
  <Card.Title>blahblah</Card.Title>
  <Card.Divider />
</Card>

I want to create a component with such sub component like Title and divider.

I can create a component like this.

class A extends Component {
}

How can I add a subcomponent(let's say Title) to A component?

2

There are 2 answers

2
Reza Shafie On

Subcomponents are objects like the component itself but, they are passed to the main component as its keys. These two liks can be good help:

https://dev.to/ms_yogii/create-react-subcomponents-in-a-simple-way-5h1f

https://dev.to/shayanypn/buckle-with-react-sub-component-10ll

0
Zeta On

According to Reza's answer, I made a class component. Is this the right way? Please correct me if there is something wrong..

class Left extends Component {
  static id = 'Left';
  render() {
    return (
      <View>
        {this.props.children}
      </View>
    );
  }
};
class Right extends Component {
  static id = 'Right';
  render() {
    return (
      <View>
        {this.props.children}
      </View>
    );
  }
};
class SideBySide extends Component {
  protected others = [];
  constructor(props) {
    super(props);
    for(let i of this.props.children) {
      if(i.type.id == 'Left') this.left = i;
      else if(i.type.id == 'Right') this.right = i;
      else this.others.push(i)
    }
  }
  render() {
    return (
      <View style={{flexDirection: 'row', }}>
        {this.left}
        {this.right}
        {this.props.others}
      </View>
    );
  }
};
SideBySide.Left = Left;
SideBySide.Right = Right;