[Javascript] Toggle Between Grid and List View in React

This article will walk you through the process of changing the layout view from grid to list and back. Note: This article is a follow up from, Render Fetched Data from a GraphQL API in React.

What we’re building.

So far, we have rendered the Rick and Morty API data with a grid layout using the Bootstrap CSS framework and Sass.

Declaring State

The first step is to define the state and its default value in the App.js. Here, toggleViewand setToggleViewrefer to the state value and updater function returned on invoking useState with some initialState. Use a boolean to toggle between the grid and list view. Here, the default value (true) means it’s in grid view, and if it’s false, it will be in list view.

const [toggleView, setToggleView] = useState(true);

Create a button that allows you to toggle between the grid and list view. Add the onClick() property with a console.log() to test that the functionality works as expected.

<div className="trigger-button" onClick={() => { console.log('clicked') }}>

Once you have the click functionality working, swap out the console.log for the updater function and pass in the toggleView state as the parameter:

<div className="trigger-button" onClick={() => setToggleView(!toggleView)}>

We will be using a ternary operator to implement the functionality of the toggle between the grid view and list view. If the default state is true, meaning the grid view is rendered, a list icon will show. If the state is false, then the list view is rendered and the grid icon will show.

Bootstrap Icons

First, install Bootstrap Icons:

$ npm install bootstrap-icons

Then, add it to the custom.scss file, just below the Bootstrap import:

@import "../node_modules/bootstrap/scss/bootstrap.scss";
@import "../node_modules/bootstrap-icons/font/bootstrap-icons.css";

Next, write the ternary operator logic:

{toggleView ? "list" : "grid"}

Search for the grid and list icons:

Swap out the text in the ternary operator to conditionally render the icons we will be using. Be sure to wrap each code snippet in parentheses.

{toggleView 
? (
    <i className="bi bi-list"></i>
  ) : (
    <i className="bi bi-grid"></i>
  )
} 

We want this button to be fixed to the top right corner of the browser window, since we’ve already given the button a class name, trigger-button , use fixed positioning to remove the button from the normal flow and offset it 30 pixels from the right.

Make the icon bigger by adjusting the font-size.

.trigger-button {
    position: fixed;
    right: 30px;
}

.trigger-button i {
  font-size: 2em;
}

Finally, modify the className="row" to include the ternary that toggles between the row which renders the characters in grid layout and the col which renders the characters in list layout.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

<div className={toggleView ? "row" : "col"}>

Passing Down Props

The styling for the list view is still not correct. To get this to look like the mockup GIF above, pass the toggleView prop down to the CharacterInfo component:

<CharacterInfo 
  key={character.id} 
  character={character} 
  toggleView={toggleView} 
/>

The CharacterInfo functional component can then take the toggleView prop as a parameter.

const CharacterInfo = ({ character, toggleView }) => {}

Lucky for us, we can use the same ternary operator logic to conditionally render different layouts for the grid and the list.

{toggleView ? "grid" : "list"}

Remember, we want to see the list icon when we are in grid view and the grid icon when we are in list view. Therefore, we need our default toggleView state to be the grid:

 const CharacterInfo = ({ character, toggleView }) => {
    return(
        <div className="col mb-5">
            {toggleView ? (
                <div className="card">
                    <img src={character.image} className="card-img-top" alt={character.name}></img>
                    <div className="card-body" style={{ width: "18rem" }}>
                        <h4 className="card-title">{character.name}</h4>
                        <p className="card-text">
                            {character.gender}
                            <span className="float-end">{character.species}</span>
                        </p>
                    </div>
                </div>
            ) : (
                <div className="list-view">
                    <div className="row">
                        <div className="col-2">
                            <img src={character.image} className="rounded float-start" alt={character.name}></img>
                        </div>
                        <div className="col-10">
                            <h2 className="card-title">{character.name}</h2>
                            <h3 className="card-text">{character.gender}</h3>
                            <h3 className="card-text">{character.species}</h3>
                        </div>
                    </div>
                </div>
            )}

        </div>
    )
}

export default CharacterInfo

The grid layout is what was originally created in the previous article. Now, we need to create a layout for the list view. Let’s start by creating a new CSS class, list-view which duplicates the box-shadow and border style of the card element.

.list-view {
  padding: 5px;
  box-shadow: 5px 5px 1px 1px $softBlack;
  border: 2px solid $softBlack;
  border-radius: 8px;
}

Next, we will use Bootstrap’s grid system to create two columns for each character — one with the image and the other with the text content. You can copy-paste this snippet from the Bootstrap documentation.

<div className="list-view">
  <div className="row">
    <div className="col-2"></div>
    <div className="col-10"></div>
  </div>
</div>

Inside the col-2 element we will place the image and give it a class name rounded float-start .

<div className="col-2">
  <img src={character.image} className="rounded float-start" alt={character.name}></img>
</div>

Give the image a width of 200px to overwrite the the Bootstrap classes rounded float-start:

.list-view img {
  width: 200px;
}

Inside the col-10 element, we will place the text content — namegender and species. You can also add the character’s statustype and origin.

<div className="col-10">
    <h2 className="card-title">
        Name: {character.name},
        <small className="text-body-secondary"> ({character.gender})</small>
    </h2>
    <p className="h3">
        Species: {character.species}
    </p>
    <p className="h3">Type: {character.type === "" ? "Unknown" : `${character.type}`}</p>
    <p className="h3">Origin: {character.origin.name === "unknown" ? "Unknown" : `${character.origin.name}`}</p>
</div>

Some of the properties have empty string values or unknown values. Use a ternary operator to conditionally render the text you’d like to show instead.

Conclusion

The previous steps walk through the process of toggling the layout view between grid and list using conditional rendering in React, a few lines of custom CSS and Bootstrap classes.

 
 

[출처] https://medium.com/@layne_celeste/toggle-between-grid-and-list-view-in-react-731df62b829e

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
20 [nest.js] [NestJS] NestJS 구조 이해를 위한 필수 개념 정리 - Node.js/TypeScript/Express 비교 포함 file 졸리운_곰 2025.12.12 501
19 [node.js 개발] Apache Reverse Proxy 설정(아파치와 노드 연동) file 졸리운_곰 2024.03.17 300
18 [node.js 개발] PM2로 Node.js 앱 프로세스 배포하기 file 졸리운_곰 2024.03.16 405
17 [node.js 개발] PM2를 활용한 Node.js 무중단 서비스하기 file 졸리운_곰 2024.03.16 517
16 [node.js 응용] Next.js : Next.js14에 Mysql연결하기 졸리운_곰 2024.03.03 379
15 [node.js 응용] Node.js에서 다른 파일의 함수를 "include" 하는 방법 졸리운_곰 2024.02.28 427
14 [node.js 응용] NodeJS 에서 mqtt 사용하기 file 졸리운_곰 2024.02.23 399
13 [node.js 응용] Next.js 기본 개념정리 file 졸리운_곰 2024.02.23 432
12 [node.js 응용] ejs 사용설명서 file 졸리운_곰 2023.11.25 371
11 [node.js 응용] Build a Node.js Proxy Server in Under 10 minutes! file 졸리운_곰 2023.05.07 468
10 [node.js 응용] node - pm2로 node.js 프로세스 관리하기 - 기본 명령어, 실행하기 file 졸리운_곰 2023.04.25 407
9 [node.js 응용] Node.js | MySQL과 연동(mysql모듈) - CRUD 2/2 졸리운_곰 2023.03.31 231
8 [node.js 응용] Node.js | MySQL과 연동(mysql모듈) - CRUD 1/2 file 졸리운_곰 2023.03.31 484
7 [node.js 응용] PM2 - Node.js 프로세스 관리 도구 file 졸리운_곰 2021.12.10 409
6 [node.js][nodejs] [Linux] 리눅스 내 Node.js 및 NPM 최신 버전으로 유지하기 file 졸리운_곰 2021.10.11 484
5 [node.js][typescript] 5분 안에 보는 TypeScript file 졸리운_곰 2021.07.03 428
4 Getting started with RabbitMQ and Node.js file 졸리운_곰 2019.05.09 466
3 [Node.js + RabbitMQ] Node.js + socket.io + RabbitMQ 이용한 실시간 메시지 처리 file 졸리운_곰 2019.05.09 352
2 node.js 서버 장애시 자동 재시작 설정 [forever 사용] 졸리운_곰 2019.01.24 884
1 Express 앱용 프로세스 관리자 졸리운_곰 2018.10.16 603
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED