Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React: How to implement Component.SubComponent

Tags:

reactjs

I saw some example code like this:

import React from 'react'
import MyComp from 'my-comp'

const MySubComp = MyComp.MySubComp

class Page extends React.Component {
  render() {
    return (
      <MyComp>
        <MySubComp/>
      </MyComp>
      )
  }
}

How to implement the syntax MyComp.MySubComp?

Does it has a terminology?

like image 446
Littlee Avatar asked Dec 15 '16 03:12

Littlee


2 Answers

In your example, MySubComp is a static class member of MyComp, you can easily implement it like that :

export default class MyComp extends Component {
   // ...
}

MyComp.MySubComp = class MySubComp extends Component {
   // ...
}
like image 129
Freez Avatar answered Oct 22 '22 00:10

Freez


Similarly to Freez's answer, for functional components you can append the sub-component to it like so:

export default function MyComp(props) {
    return (
        <div>Main component</div>
    );
}

MyComp.MySubComp = function MySubComp(props) {
    return (
        <div>Sub component</div>
    );
}

// Alternative way
MyComp.MySubComp = (props) => <div>Sub component</div>

They can be consumed this way:

<MyComp>
    <MyComp.MySubComp />
</MyComp>

Note: The first way repeats the name of the component. The explanation for that is the first name is the attached sub-name of the other function, and the second name is the name of the actual component, which will be displayed in React Dev Tools. Without it, dev tools will just display "Anonymous" instead.

like image 1
Magnus Bull Avatar answered Oct 22 '22 00:10

Magnus Bull