Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS Component with "sub-components"

I am quite new to ReactJS and started to make some components like this:

class Row extends React.Component {
    render() {
        return (
            <div className={"row w-100 ml-0 mr-0 " + this.props.className}>
                {this.props.children}
            </div>
        );
    }
}

What I want to achieve now is that this component has "sub-components" (I don't know the right word for it) like or something similiar.

Do I have to create another component for that or is it possible to implement that in one component?

Edit:

I have this component which already has childs inside:

<div className="custom-card">
    <Card>
        <CardHeader onClick={this.toggle} className={"card-header " + ((!this.props.readOnly && this.props.headerCtrl) && "pt-0")}>
            <CardTitle className="card-title d-flex justify-content-between">
                <p>{this.props.title}</p>
            </CardTitle>
        </CardHeader>
        <Collapse isOpen={this.state.collapse}>
            <CardBody className="card-body">
                {this.props.children}
            </CardBody>
        </Collapse>
    </Card>
</div>

But I also want that the user can specify which component should be displayed in the cardheader. So that there can not only be a <p> but also a <input> and so on.

like image 729
mantaplatte Avatar asked Apr 28 '26 06:04

mantaplatte


1 Answers

If I understand you correctly, you want multiple placeholders instead of just the one children. Luckily seeing as React elements are just JavaScript objects you can pass them as props.

When you have a component (<CustomCard>) with a render method like the one in your question (unchanged):

<div className="custom-card">
  <Card>
    <CardHeader onClick={this.toggle} className={"card-header " + ((!this.props.readOnly && this.props.headerCtrl) && "pt-0")}>
      <CardTitle className="card-title d-flex justify-content-between">
        <p>{this.props.title}</p>
      </CardTitle>
    </CardHeader>
    <Collapse isOpen={this.state.collapse}>
      <CardBody className="card-body">
        {this.props.children}
      </CardBody>
    </Collapse>
  </Card>
</div>

You can pass custom components for the title like so:

<CustomCard title={<SpecialTitle>My special title</SpecialTitle>}>
  My card body!
</CustomCard>
like image 58
Wazner Avatar answered Apr 30 '26 19:04

Wazner