前提
画面遷移の前にサムネイルのサイズ(今回は幅だけ)を取得し、画面遷移先でその値を取得しようと試みているが取得できる値がnullになってしまう。Template.jsの12行目の結果でnullになってしまう。
実現したいこと
HomePage.jsで取得したサムネイル画像の表示されているサイズを取得し、Template.jsでその値を取得してアニメーションのInitialとして使いたい。
該当のソースコード
HomePage.js
import
1import Thumbnail from '../components/Thumbnail'; 2import EmptyImage from '../images/empty.webp'; 3import SectionTitle from '../components/SectionTitle'; 4import { Link } from 'react-router-dom'; 5 6// This compornent has function of showing each work thumbnails and links. 7 8 9function HomePage() { 10 11 const elm = useRef(null); 12 const [state, setState] = useState(0); 13 14//ここでサムネイル画像のサイズ(横幅)を取得している 15 useEffect(() => { 16 if (elm.current) { 17 const { clientWidth: thmbnaiilWidth } = elm.current; 18 setState(thmbnaiilWidth); 19 } 20 }, []); 21 22 //Click時に値が取れているか 23 const checkClick = () =>{ 24 console.log(state); 25 } 26 27 28 return ( 29 <div className='home-page'> 30 <SectionTitle title={'Works'} /> 31 32 <div className='container'> 33 <div className='list-container'> 34 <div className='thumbnails' ref={elm}> 35 <Link to={{pathname: '/template', state: { test: state }}} onClick={checkClick}> //Template.jsに値を渡す 36 <Thumbnail thumbnailImage={EmptyImage} workTitle={'Work Title'} category={'Category'}/> 37 </Link> 38 </div> 39 </div> 40 41 </div > 42 <SectionTitle title={'Test'} /> 43 </div> 44 ) 45 46} 47 48export default HomePage
Template.js
import
1import { useLocation } from 'react-router-dom'; 2 3//images 4import EmptyImage from '../images/empty.webp'; 5 6const transition = { duration: 2, ease: [0.6, 0.01, -0.05, 0.9] }; //Animationのスピード 7 8 9const Template = () => { 10 11 const location = useLocation(); 12 console.log(location.state); 13 14 return ( 15 <motion.div 16 initial={{opacity: 0}} 17 animate={{opacity: 1}} 18 19 className='work-detail-page'> 20 <div className='container'> 21 22 <motion.img 23 initial={{width: `${location.state?.test || 0}px`, height:"20px"}}//ここに取得したコンテナの幅や高さを持ってくる 24 animate={{width:"100%", height:"100%", transition: { delay: 0, ...transition }}} 25 26 className='hero-img' 27 src= {EmptyImage} 28 alt='test-images'/> 29s 30 <div className='work-contents'> 31 32 <div className='title-section'> 33 <h1>Title</h1> 34 35 <div className='info'> 36 <h4>サンプル</h4> 37 </div> 38 39 <p className='work-text'>サンプルテキスト</p> 40 </div> 41 </div> 42 43 </div> 44 </motion.div> 45 ) 46} 47 48export default Template 49
試したこと
値の渡し方をuseNavigate + useLocationで試したが同じ結果であった。
クリック時にはまだ値は正常に取得できているが、遷移先の写ったタイミング(Template.jsの12行目)の結果でnullになってしまう。
補足情報(FW/ツールのバージョンなど)
使用しているバージョン
├── framer-motion@8.4.3
├── react-dom@18.2.0
├── react-router-dom@6.5.0
├── react-scripts@5.0.1
├── react@18.2.0
<Link to='/template' state={{ test: state }} 〜 > かな。
https://stackoverflow.com/questions/70214766/i-can-not-get-the-state-from-react-router-link-component-using-uselocation-so-h
できるかどうかわかりませんが、下記のサイトでは
<Link to={"/about"} state={{ test: "test" }}> のようにstateを渡しています。
https://zenn.dev/lilac/articles/c40b35fe3184da
回答1件