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/>
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/>
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>
);
}
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>