[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

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
254 [JavaScript] JavaScript / Object / Element.removeAttribute() / 요소의 속성을 제거하는 메서드 졸리운_곰 2024.05.18 402
253 [JavaScript] How to select all tag elements with JS 졸리운_곰 2024.05.18 11105
252 [HTML] DIV를 통해 일반적인 헤더를 만들어 보자. file 졸리운_곰 2024.05.18 369
251 [JavaScript] 자바스크립트 javascript 정규식 replace html 제거 태그 제거 졸리운_곰 2024.05.18 616
250 [HTML] Set display:none not working. : display : none 이 동작하지 않습니다. 졸리운_곰 2024.05.18 499
249 [JavaScript] Checking if iframe contents are loaded? : iframe 로딩 완료 이벤트 확인 졸리운_곰 2024.05.18 533
248 [HTML] How TO - Get Iframe Elements : javascript로 iframe 요소에 접근 졸리운_곰 2024.05.18 486
247 [HTML] form submit redirection 리다이렉션 없이 자기 페이지에 결과 표시 : <form> 태그의 target 속성 졸리운_곰 2024.05.17 485
246 [HTML] form submit redirection 리다이렉션 없이 자기 페이지에 결과 표시 : iframe으로 form 응답값 받기 졸리운_곰 2024.05.17 481
245 [JavaScript] 자바스크립트 DIV 보이기, 숨기기(토글) 졸리운_곰 2024.05.16 501
244 [JavaScript] [JS] XPath로 element 찾기 file 졸리운_곰 2024.05.16 495
243 [JavaScript] How to clone (and restore) a DOM subtree 졸리운_곰 2024.05.16 324
242 [JavaScript] Force-DOM-reflow-JS 졸리운_곰 2024.05.16 522
241 [JavaScript] Javascript XPath를 이용해서 Dom Element 가져오기 졸리운_곰 2024.05.15 496
240 [JavaScript] Introduction to using XPath in JavaScript 졸리운_곰 2024.05.15 504
239 [JavaScript] JavaScript :: 요소 가져오기 file 졸리운_곰 2024.05.15 579
238 [JavaScript] lastIndexOf() : String에서 원하는 값의 마지막 위치(index) 찾기 졸리운_곰 2024.02.28 366
237 [JS] 문자열의 위치 찾기 & 문자열 추출하기 file 졸리운_곰 2024.02.28 573
236 [JavaScript] lastIndexOf() : String에서 원하는 값의 마지막 위치(index) 찾기 졸리운_곰 2024.02.28 544
» [Javascript] Toggle Between Grid and List View in React file 졸리운_곰 2024.02.23 276
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED