⚠Disclaimer
This article has been translated using ChatGPT by the author; as such, some parts may not be accurately represented or contextually appropriate. For the original content, please refer to the link provided below.
https://zenn.dev/bony_chops/articles/34969d261d7553
Preface
While creating my own portfolio, I realized that my professional experiences were listed in ascending chronological order.
However, looking at Wantedly, I noticed that the experiences are listed in descending order. I want my format to align with this.
But now, reversing the order of this many components would be a huge task...
Strategy
For instance, we aim to reverse the order of the following components.
<div>
<p>a</p>
<p>b</p>
<p>c</p>
</div>
↑I want the order to be c, b, a.
- Create a
<ReverseComponent>
- Enclose the target components with it
Creating the ReverseComponent
First, we will create the ReverseComponent as follows
import React from "react";
export default function ReverseComponent(props: {
children: React.ReactNode;
}) {
const { children } = props;
const reverse = props.reverse ?? true;
if (Array.isArray(children)) {
return children.slice().reverse();
}
return children;
}
When multiple components are passed to children, they are passed as an Array. So, if it is an Array, we use .reverse()
to reverse the order.
About .slice
Since children
are passed as readOnly, we cannot use the destructive .reverse()
. So, we use .slice()
to make a shallow copy and use it.
Enclosing the Components
<div>
+ <ReverseComponent>
<p>a</p>
<p>b</p>
<p>c</p>
+ </ReverseComponent>
</div>
Tada 🎉
Making it Switchable
import React from "react";
export default function ReverseComponent(props: {
children: React.ReactNode;
+ reverse?: boolean;
}) {
const { children } = props;
+ const reverse = props.reverse ?? true;
if (Array.isArray(children)) {
- return children.slice().reverse();
+ return reverse ? children.slice().reverse() : children;
}
return children;
}
<div>
- <ReverseComponent>
+ <ReverseComponent reverse={false}>
<p>a</p>
<p>b</p>
<p>c</p>
</ReverseComponent>
</div>
Now you can dynamically switch between ascending and descending order.
Applying to the Portfolio
It was extremely easy to reverse the order by just creating one component. Also, I made a button to reverse the order as a bonus.
Top comments (0)