how do you do dot notation react components with react hooks?

Viewed 964

I've seen some libraries use dot notation components in React

e.g.

<Menu>
   <Menu.Item>Item 1</Menu.Item>
   <Menu.Item>Item 2</Menu.Item>
</Menu>

this is using the static keyword in the class component e.g.

const Item = () => ...code

class Menu extends Component {
  static Item = Item

  ...code

Since functional components with React hooks aren't class Components, can this pattern still be used somehow with functional components (e.g. accessing the prototype or something?)

Can this still be done?

1 Answers

This pattern is called Compounded Components. To use the pattern with functional components, just add the sub-component (Item) as a property of a the main component (Menu).

You can find more information in Kent C. Dodds article - React Hooks: Compound Components .

const Item = ({ children }) => (<li>{children}</li>);

const Menu = ({ children }) => (<ul>{children}</ul>);

Menu.Item = Item;


ReactDOM.render(
  <Menu>
     <Menu.Item>Item 1</Menu.Item>
     <Menu.Item>Item 2</Menu.Item>
  </Menu>,
  root
);
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<div id="root"></div>

Related