'React jsx attribute avoid duplicate attribute name
I am using Nextjs I dont really know to describe my question but here is an example.
In my code, I got few
const pathname = router.pathname
<NavItem pathname={pathname} ... />
Is there a way to avoid that kind a duplicate name? To make it shorter? like this may be
<NavItem {pathname} ... />
I dont know if its possible but it's not the first time that I am looking for the kind of writing style
Thanks
Solution 1:[1]
The only way I can think of accomplishing that is using the spread syntax. It may be overkill for one prop, but it can be useful for many.
You first define an object like this.
const { pathname } = router;
const shortened = {
pathname,
};
Let's see it line by line.
The first line is using object destructing to get the pathname
key from router
. This will simplify the object written later.
The second-to-fourth lines define an object called shortened
(or whatever you want to call it). Inside of it, we pass in pathname
as both a key and value in one (like a 2-in-1). This simply is a shorthand way of saying pathname: pathname
.
Now, let's move on to the JSX!
Let's use the JSX here, and see what it does.
<NavItem {...shortened} />
Basically, add that it is doing is using the spread syntax (...
) to "spread" the object so that it looks like this when parsed.
<NavItem pathname={pathname} />
So, it is just getting the key and value and spreading it out like that.
You can also add more keys and values to your object, without changing your JSX as well, which makes it easier and faster to type! It also may look better (depending on who you are).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Community |