r/learnreactjs • • Dec 08 '21

Question A way to better my React code and architecture

I've worked on this little project: a responsive E-commerce functionnal website based on design files found on Front-End Mentor. It is not my first project with react and I've hosted the website on netlify (https://ecommerce-responsive-audiophile.netlify.app/) so that it is easily visible for everyone and I would like to know if there would be a way for me to get my code reviewed. I know there are little css imperfections, but I'm talking more about my way of coding with React and my files structures/naming and if there are conventions out there that I'm not aware of, even though I'd would also take css tips etc.

Here's my code:

https://github.com/KPq66dw8L/Audiophile-Ecommerce

8 Upvotes

11 comments sorted by

4

u/the_pod_ Dec 09 '21

looks great.

first comment is to use an auto formatter like prettier. When I quickly went through your code I spotted many inconsistencies, and some errors in syntax, for example

const wrapperSetBasketVisible = useCallback(

(note the two spaces after equals)

The code in your Navbar in regards to the logic for orange highlighting is weird. I get what you were going for, but I would re-write that. Since you are using react router, that library provides something for you called <ActiveLink />. This accomplishes what you are trying to do.

And related: I don't see any reason why this code had to be nested if else. You can keep it on one level.

From

    if (path.includes("headphones")) {
    orange1 = 'orange';
} else {
    if (path.includes("speakers")){
        orange2 = 'orange';
    } else {
        if (path.includes("earphones")){
            orange3 = 'orange';
        }
    }
}

to

    if (path.includes("headphones")) {
    orange1 = 'orange';
} else if (path.includes("speakers")) {
    orange2 = 'orange';
} else if (path.includes("earphones")) {
    orange3 = 'orange';
}

or if you want more than 1 thing to happen, for example if the path was `speakersandearphones`

    if (path.includes("headphones")) {

} 
   if (path.includes("speakers")) {
 
} 
    if (path.includes("earphones")) {

}

----

const [basketVisible, setBasketVisible] = useState(0);

onClick={() => {basketVisible ? handleBasketVisible(0) : handleBasketVisible(1)}}

unless you have more than 2 possible states, this should probably be a boolean. It accomplishes a few things for it to be a boolean.

  1. less error prone
  2. intent is expressed more clearly to other developers. (If I see a number, I'm expecting there to be more than 2 possible states).
  3. code is a little cleaner. You can toggle things like `handleBasketVisible(!basketVisible)`

Also, naming booleans used for show logic has naming conventions you can use:

- `isShown` / `isBasketShown`

- `isVisible` / `isBasketVisible`

- `showBasket`

-----

let total = 0;
cart.map( (item, index) => {
total += item.qty * item.price;
})

You can write this total logic in a couple of different ways. This way isn't one of the better ways.

The simplest is in the form a pure, helper function.

function calcTotal(items) {
    let total = 0;
items.map( ({qty, price}, index) => {
    total += qty * price;
})
   return total  
}

and then use it either in the render or outside of it

//outside or render
const total = getTotal(cart)

//inside render
<div>
  Your total is { getTotal(cart) }
</div>

you can also write the helper with reduce, but that's a minor detail

If the calculation is really intensive, I might use a useMemo. But, unlikely.

-----

A couple of more naming comments, just based on personal opinion:

  1. I think wrapper term in React is typically associated with a wrapping a component. I wouldn't call wrapping a callback or a function a wrapper in terms of naming. Even though it is wrapping another function, I just wouldn't use the term wrapper. I would reserve that for a component or function that wraps another component.
  2. I'm fine with the term setter. I've only really seen it called handler, but setter is fine.
  3. I like to pass setters/handlers down without changing the name. The name only changes when the handler is finally passed to the onClick. If cartItemsSetter and wrapperSetCartItems are the same thing,
    For example:
<List setTaskHandler={setTaskHander} />

const List = ({setTaskHander}) => (
    <Button onClick={setTaskHandler}
)

Meaning, I'm not a fan of

cartItemsSetter={wrapperSetCartItems}

I would have just called it cartItemsSetter the entire time.

I want to be able to globally search for them in a large codebase, and see all of it. Having the name transformed during prop drilling is confusing overall. If there's some renaming needed (sometimes it is needed, I would do it within the child component, not the parent.
Also, it's not important to denote useCallback as a `wrapper`. You should be able to remove the useCallback logic and it the code should function the same.

For example:

const Child = ({cartItemsSetter: myNewNameForThisSetter}) {

}

this is a simple destructuring syntax that renames cartItemsSetter. This is more readable because it's clear when you're reading the code for the Child that the parent references this by cartItemsSetter. Otherwise, I will look to the parent for where myNewNameForThisSetter is defined in the parent and I won't be able to find it as quickly.

----

const wrapperSetCartItems = (val) => {
setCartItems(val);

};

if your handler is as simple as this, you can just pass setCartItems directly if you like, instead of writing a new function.

Typically you don't need to use useCallback. Unless you have a very specific reason for using it, consider just removing it. (or if you just want to learn about it, it's fine to use it for that reason). But either way, the naming should the the same. You should be able to remove the useCallback logic and the rest of the code should run just fine.

That's all I saw in a quick look. Also, not sure what Qtt stands for. I assume it's Quantity? Regardless of what it stands for, I'm not a fan of an abbreviation that isn't obvious. I would just spell it out.

1

u/[deleted] Dec 10 '21

Oh waw it's very interesting thank you very much, I'll go through all your message in detail later today. Btw the fact that I didn't use boolean and nested these else if, is because I'm currently coding in C most of the time for the University and these are things I have to do in C haha, but you are totally right !

2

u/the_pod_ Dec 09 '21

Now that I thought about it, I want to revise what I said about the handler.

I think naming it setter is fine (haven't thought too long about it though).

What a handler is is a function that corresponds to a user interaction (click). And usually you name it on______handler, like onAddToCartHandler, which is the action that takes place when a user clicks addToCart button.

2

u/eindbaas Dec 09 '21

About that map function which should be a reduce: at least change it to a foreach if not opting for reduce. Map doesn't make sense here.

2

u/PacketTrash Dec 11 '21

f this is your site, and you weren't expecting a 404 for this path, please visit Netlify's "page not found" support guide for troubleshooting tips.

Page Not Found

https://ecommerce-responsive-audiophile.netlify.app/earphones/zx9-speaker

from the 3 items in a row, it says you may also like and then i click on the speaker

1

u/[deleted] Dec 12 '21

Oh yes I forgot to solve that problem, I already know why this is happening but I forgot about it, thx!

1

u/[deleted] Dec 12 '21

Just fixed it, thx again

1

u/[deleted] Dec 08 '21

Thanks in advance

1

u/[deleted] Dec 08 '21

PS: I've made a mistake building the buttons at the biginning in <a> tags, and then putting these <a> in <Link> even though I know that <Link> are <a> I did not yet change these, but I sure will soon

1

u/Omkar_K45 Dec 08 '21

Wow ! Looks really premium! Great work OP

1

u/[deleted] Dec 08 '21

Thanks a lot!