0

I found such a notation in the code, but I don't know how to interpret it. What do two components connected by a dot mean in React?

<OneComponent.TwoComponent/>
Yerba Mate
  • 113
  • 2
  • 9
  • 1
    It's just accessing a property, like anywhere else in JavaScript. See examples in e.g. https://stackoverflow.com/q/60882627/3001761. – jonrsharpe Aug 30 '22 at 09:39

1 Answers1

1

This is a way of organising a compound component.

Essentially, a javascript object that communicates the intent that the collection of components work together and thus should be used together.

// Compound.js

function Root({ children }) {
  return (
    <>
      <p>root</p>
      {children}
    </>
  );
}

function Child1() {
  return <p>child 1</p>;
}

function Child2() {
  return <p>child 2</p>;
}

export default {
  Root,
  Child1,
  Child2
};

// App.js

import Compound from "./Compound";

export default function App() {
  return (
    <Compound.Root>
      <Compound.Child1></Compound.Child1>
      <Compound.Child2></Compound.Child2>
    </Compound.Root>
  );
}

Edit Simple compound component


It is also worth remembering that JSX in react is mostly just syntactic sugar for a bunch of nested calls to React.createElement until it gets to the bottom and returns a html element or a text element.

React.createElement returns a javascript object that describes the element (type, props, children, etc). And you can add a custom key/value pair to a javascript object with dot notation.

const myComponent = React.createElement('p', null, 'Hello world')
myComponent.customTextProperty = 'my custom property value'
myComponent.myCustomObjectProperty = {foo: 'bar'}

console.log(myComponent)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
ksav
  • 20,015
  • 6
  • 46
  • 66