Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 822
Ruegen Avatar asked Oct 28 '25 08:10

Ruegen


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>
like image 65
Ori Drori Avatar answered Oct 31 '25 01:10

Ori Drori



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!