Nghiệp
Nghiệp

Reputation: 4718

How to design component layout reasonable in React?

I have two options in below. What should I choose?

Option 1:

in Header.jsx:

<div>
    <Logo />
    <Menu>
        <MenuItem> homepage </MenuItem>
        <MenuItem> contact </MenuItem>
    </Menu>
</div>

Option 2:

- in Header.jsx

<div>
    <Logo />
    <Menu />
</div>

- in Menu.jsx

<ul>
    <MenuItem> homepage </MenuItem>
    <MenuItem> contact </MenuItem>
<ul>

I don't know the strength or weakness of each option. tks all pro.

Upvotes: 2

Views: 550

Answers (3)

Madura Pradeep
Madura Pradeep

Reputation: 2454

Following is an official tutorial about how you should break your components.

https://facebook.github.io/react/docs/thinking-in-react.html

According to that, the component should break based on their responsibilities. They talk about single responsibility principle, that is, a component should ideally only do one thing.

Recommend to follow that.

According to that the responsibility of your menu is different. So you better make it as an another component.

Upvotes: 1

Philipp
Philipp

Reputation: 2796

If you, somewhere in your app, are using another menu it would make sense to split it. So you can reuse the components of your menu.

In a simple scenario like this you can go with the first option [1]. There is little use to split the elements into components when there simply is nothing you will do with them later. Also this piece of code is small enough to refacor later, when there is actual need to use separate components.

[1] means: I would not be surprised or annoyed when I see this piece of code. The best practices way would be to put Menu and MenuItem into own components.

Upvotes: 1

Vikram Saini
Vikram Saini

Reputation: 2771

Approach should be like think of the most modular structure so that all the components are independent of each other.And in future if you want to add a functionality then other components should remain untouched.So Approach2 is better.But everything relies on your problem statement and architecture so you need to take care of all the scenarios that might irritate you in future

Upvotes: 1

Related Questions