Home > other >  What is the peculiarity of components that are written with a dot in React?
What is the peculiarity of components that are written with a dot in React?

Time:01-29

I don't seem to understand, and studying the question gives no clue.

For example, there is a card component. We create the wrapper, then the body, then the header, then the footer. These are 4 different components.

In the wrapper, we specify that Card.Body = CardBody But why? If we add the same component, is it only about readability?

Example:

<Card>
   <Card.Body>
   ...
   </Card.Body>
   <Card.Footer>
   ...
   </Card.Footer>
</Card>

//What is difference?
<Card>
   <CardBody>
   ...
   </CardBody>
   <CardFooter>
   ...
   </CardFooter>
</Card>

CodePudding user response:

The use of the dot notation in components in React is a way to organize and group related components together. It is not necessary for the functionality of the component but rather for the readability and organization of your code. In the example provided, the <Card.Body> and <Card.Footer> components are grouped under the parent component. This allows for a clear distinction between the different parts of the component and makes it easier to understand the structure of the code.

Another advantage of using this notation is the ability to control the number of imports and variables in the scope. Instead of having to import and declare each component individually, you can group them together under a single object and import them as a whole. This can help to keep your codebase more organized and manageable.

For example, instead of having to import and declare each component individually like this:

import CardBody from './CardBody';
import CardFooter from './CardFooter';
import CardHeader from './CardHeader';

const MyComponent = () => {
    return (
        <div>
            <CardBody />
            <CardFooter />
            <CardHeader />
        </div>
    )
}

You can group them together under a single object and import them as a whole like this:

import { Card } from './Card';

const MyComponent = () => {
    return (
        <div>
            <Card.Body />
            <Card.Footer />
            <Card.Header />
        </div>
    )
}

This way you have less imports and variables in the scope, which can make your codebase more organized and manageable.

In conclusion, the use of the dot notation in React components is not a requirement but rather a convention used to organize and improve the readability of your code.

  • Related