はじめに
このような動きを作ります。
以下のサイトからWebデザインのレイアウトを探していたところ、
こちらのサイトに目が留まりましたので真似てみました。
やりたいこと
- 中央コンテンツをスクロールできる
- 中央コンテンツをスクロールしても左右コンテンツはスクロールされない
- 左右コンテンツのボタンをクリックすると該当箇所にジャンプできる
コード
App.tsx
import React, { useRef } from 'react';
import { Box, Button, Container, Flex, VStack } from '@chakra-ui/react';
import { Content1 } from './pages/Content1';
import { Content2 } from './pages/Content2';
import { Content3 } from './pages/Content3';
function App() {
const contentRef1 = useRef<HTMLDivElement>(null);
const contentRef2 = useRef<HTMLDivElement>(null);
const contentRef3 = useRef<HTMLDivElement>(null);
const handleScrollToContent = (ref: React.RefObject<HTMLDivElement>) => {
ref.current?.scrollIntoView({ behavior: 'smooth', block: 'center' });
};
return (
<>
<Flex direction="row" h="100vh" overflowY='scroll'>
<Container w="50%" h="100vh" position="relative" zIndex="20" >
<Box width="500px" h="100vh" ref={contentRef1}><Content1></Content1></Box>
<Box width="500px" h="100vh" ref={contentRef2}><Content2></Content2></Box>
<Box width="500px" h="100vh" ref={contentRef3}><Content3></Content3></Box>
</Container>
<VStack spacing={4} w="50%" position="fixed" right="0" top="50%" zIndex="30">
<Button onClick={() => handleScrollToContent(contentRef1)}>中央コンテンツ1へ</Button>
<Button onClick={() => handleScrollToContent(contentRef2)}>中央コンテンツ2へ</Button>
<Button onClick={() => handleScrollToContent(contentRef3)}>中央コンテンツ3へ</Button>
</VStack>
</Flex>
</>
);
}
export default App;
ポイント
- レイヤー構造をつくる
左右コンテンツのz-indexを高くすることで、スクロール時の画面の動きを中央コンテンツと切り離すことができます。
おわりに
Webデザインのレイアウト集は眺めているだけでも面白いですね。