현재 버전

리액트 useRef 관련해서 질문합니다.


스크롤 박스에 접근하려고 합니다.

useRef를 선언했습니다.


문제는 TypeError: Cannot read property 'scrollTop' of null

가 뜹니다.

이거 해결해서 작동시키려면 어떻게 해야하나요?


useRef를 제대로 연결한 것인지???
스크롤 설정을 제대로 한것인지???
null인 경우 에러를뿜고,

숫자 0을 기본 값으로 할 경우 함수가 작동하지 않습니다.

useEffect(() => {
      scrollBox.current.scrollTop();
  }, [location]);

에서 scrollTop을 속성이 null값이라고 오류가 뜹니다.
그런데, scroll을 쓰려면 null을 선언해야하지 않나요???

TypeError: Cannot read property 'scrollTop' of null

import React, { useState, useEffect, useRef } from "react";
import { Link } from 'react-router-dom';
import styled from "styled-components";
import Nav from './Nav';

const Images = () => {
  const [data, setData] = useState();
  const [location, setLocation] = useState();
  const scrollBox = useRef(null);

  // 이미지 자료 긁어오기.
  useEffect(()=> {
    fetch(`http://localhost:3000/data/MockupData.json`)
      .then(res => res.json())
      .then(res => {
        setData(res)
      })
      .catch (error => {
        console.log(error);
      });
  }, []);

  //마우스 스크롤 이벤트 작동
  useEffect(() => {
      scrollBox.current.scrollTop();
  }, [location]);

  // const activeOverScrollEvent = () => {
  //   if(window.scrollTop > 400) {
  //     window.scrollTopView(window.scrollTopView(0, 1600))
  //   }
  //   if(window.scrollTop > 1800) {
  //     window.scrollTopView(window.scrollTo(0, 3400))
  //   }
  //   if(window.scrollTop > 3600) {
  //     window.scrollTopView(window.scrollTo(0, 5100))
  //   }
  //   if (window.scrollTop > 5300) {
  //     window.scrollTopView(window.scrollTo(0, 6800))
  //   }
  // };

  return(
    <>
      <Nav />
      <ImagesWrap>
        <ImagesBox>
          {data && data.car.map((el, i)=> {
            console.log(i);
            return (
              <>
                <picture className="images" key={i} ref={scrollBox}>
                  <MiddleBox>
                    <ModelTitle>{el.name}</ModelTitle>
                    <SubTitle>
                      <Link className='subLink' to="">{el.riding}</Link>
                    </SubTitle>
                  </MiddleBox>
                  <UnderBox>
                    <OrderLink>{el.order}</OrderLink>
                    <DetailLink>{el.detail}</DetailLink>
                  </UnderBox>
                  <Imgtag src={el.img_src} alt={el.img_alt} />
                </picture>
              </>
            )
          })
          }
        </ImagesBox>
      </ImagesWrap>
    </>
  )
}

export default Images;

const ImagesWrap = styled.div``; // 최상단 랩핑

const ImagesBox = styled.section``;

const Imgtag = styled.img`
  display: grid;
  width: 1fr;
  height: 1fr;
  max-width: 2048px;
  justify-content: center;
`;

const MiddleBox = styled.div`
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  flex-direction: flex-end;
  align-items: center;
  z-index: 1;
  position: absolute;
  left: 50%;
  margin-top: calc(16vh + 20px);
`;

const ModelTitle = styled.h1`
  display: inline-block;
`;
const SubTitle = styled.h2`
  .subLink {
    
  }
`;

const UnderBox = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: flex-end;
  flex-flow: 1;
`;

const OrderLink = styled(Link)``;
const DetailLink = styled(Link)``;

수정 이력

2021-01-31 10:09:48 에 아래 내용에서 변경 됨 #3

스크롤 박스에 접근하려고 합니다.

useRef를 선언했습니다.


문제는 TypeError: Cannot read property 'scrollTop' of null

가 뜹니다. 이거 해결해서 작동시키려면 어떻게 해야하나요?

useEffect(() => {
      scrollBox.current.scrollTop();
  }, [location]);

에서 scrollTop을 속성이 null값이라고 오류가 뜹니다.
그런데, scroll을 쓰려면 null을 선언해야하지 않나요???

TypeError: Cannot read property 'scrollTop' of null

import React, { useState, useEffect, useRef } from "react";
import { Link } from 'react-router-dom';
import styled from "styled-components";
import Nav from './Nav';

const Images = () => {
  const [data, setData] = useState();
  const [location, setLocation] = useState();
  const scrollBox = useRef(null);

  // 이미지 자료 긁어오기.
  useEffect(()=> {
    fetch(`http://localhost:3000/data/MockupData.json`)
      .then(res => res.json())
      .then(res => {
        setData(res)
      })
      .catch (error => {
        console.log(error);
      });
  }, []);

  //마우스 스크롤 이벤트 작동
  useEffect(() => {
      scrollBox.current.scrollTop();
  }, [location]);

  // const activeOverScrollEvent = () => {
  //   if(window.scrollTop > 400) {
  //     window.scrollTopView(window.scrollTopView(0, 1600))
  //   }
  //   if(window.scrollTop > 1800) {
  //     window.scrollTopView(window.scrollTo(0, 3400))
  //   }
  //   if(window.scrollTop > 3600) {
  //     window.scrollTopView(window.scrollTo(0, 5100))
  //   }
  //   if (window.scrollTop > 5300) {
  //     window.scrollTopView(window.scrollTo(0, 6800))
  //   }
  // };

  return(
    <>
      <Nav />
      <ImagesWrap>
        <ImagesBox>
          {data && data.car.map((el, i)=> {
            console.log(i);
            return (
              <>
                <picture className="images" key={i} ref={scrollBox}>
                  <MiddleBox>
                    <ModelTitle>{el.name}</ModelTitle>
                    <SubTitle>
                      <Link className='subLink' to="">{el.riding}</Link>
                    </SubTitle>
                  </MiddleBox>
                  <UnderBox>
                    <OrderLink>{el.order}</OrderLink>
                    <DetailLink>{el.detail}</DetailLink>
                  </UnderBox>
                  <Imgtag src={el.img_src} alt={el.img_alt} />
                </picture>
              </>
            )
          })
          }
        </ImagesBox>
      </ImagesWrap>
    </>
  )
}

export default Images;

const ImagesWrap = styled.div``; // 최상단 랩핑

const ImagesBox = styled.section``;

const Imgtag = styled.img`
  display: grid;
  width: 1fr;
  height: 1fr;
  max-width: 2048px;
  justify-content: center;
`;

const MiddleBox = styled.div`
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  flex-direction: flex-end;
  align-items: center;
  z-index: 1;
  position: absolute;
  left: 50%;
  margin-top: calc(16vh + 20px);
`;

const ModelTitle = styled.h1`
  display: inline-block;
`;
const SubTitle = styled.h2`
  .subLink {
    
  }
`;

const UnderBox = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: flex-end;
  flex-flow: 1;
`;

const OrderLink = styled(Link)``;
const DetailLink = styled(Link)``;
2021-01-31 09:59:20 에 아래 내용에서 변경 됨 #2

스크롤 박스에 접근하려고 합니다.

useRef를 선언했습니다.


문제는 

useEffect(() => {
      scrollBox.current.scrollTop();
  }, [location]);

에서 scrollTop을 속성이 null값이라고 오류가 뜹니다.
그런데, scroll을 쓰려면 null을 선언해야하지 않나요???

TypeError: Cannot read property 'scrollTop' of null

import React, { useState, useEffect, useRef } from "react";
import { Link } from 'react-router-dom';
import styled from "styled-components";
import Nav from './Nav';

const Images = () => {
  const [data, setData] = useState();
  const [location, setLocation] = useState();
  const scrollBox = useRef(null);

  // 이미지 자료 긁어오기.
  useEffect(()=> {
    fetch(`http://localhost:3000/data/MockupData.json`)
      .then(res => res.json())
      .then(res => {
        setData(res)
      })
      .catch (error => {
        console.log(error);
      });
  }, []);

  //마우스 스크롤 이벤트 작동
  useEffect(() => {
      scrollBox.current.scrollTop();
  }, [location]);

  // const activeOverScrollEvent = () => {
  //   if(window.scrollTop > 400) {
  //     window.scrollTopView(window.scrollTopView(0, 1600))
  //   }
  //   if(window.scrollTop > 1800) {
  //     window.scrollTopView(window.scrollTo(0, 3400))
  //   }
  //   if(window.scrollTop > 3600) {
  //     window.scrollTopView(window.scrollTo(0, 5100))
  //   }
  //   if (window.scrollTop > 5300) {
  //     window.scrollTopView(window.scrollTo(0, 6800))
  //   }
  // };

  return(
    <>
      <Nav />
      <ImagesWrap>
        <ImagesBox>
          {data && data.car.map((el, i)=> {
            console.log(i);
            return (
              <>
                <picture className="images" key={i} ref={scrollBox}>
                  <MiddleBox>
                    <ModelTitle>{el.name}</ModelTitle>
                    <SubTitle>
                      <Link className='subLink' to="">{el.riding}</Link>
                    </SubTitle>
                  </MiddleBox>
                  <UnderBox>
                    <OrderLink>{el.order}</OrderLink>
                    <DetailLink>{el.detail}</DetailLink>
                  </UnderBox>
                  <Imgtag src={el.img_src} alt={el.img_alt} />
                </picture>
              </>
            )
          })
          }
        </ImagesBox>
      </ImagesWrap>
    </>
  )
}

export default Images;

const ImagesWrap = styled.div``; // 최상단 랩핑

const ImagesBox = styled.section``;

const Imgtag = styled.img`
  display: grid;
  width: 1fr;
  height: 1fr;
  max-width: 2048px;
  justify-content: center;
`;

const MiddleBox = styled.div`
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  flex-direction: flex-end;
  align-items: center;
  z-index: 1;
  position: absolute;
  left: 50%;
  margin-top: calc(16vh + 20px);
`;

const ModelTitle = styled.h1`
  display: inline-block;
`;
const SubTitle = styled.h2`
  .subLink {
    
  }
`;

const UnderBox = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: flex-end;
  flex-flow: 1;
`;

const OrderLink = styled(Link)``;
const DetailLink = styled(Link)``;
2021-01-31 09:58:44 에 아래 내용에서 변경 됨 #1

스크롤 박스에 접근하려고 합니다.

useRef를 선언했습니다.


문제는 

useEffect(() => {
      scrollBox.current.scrollTop();
  }, [location]);

에서 scrollTop을 속성을 모른다고 하는데 어떻게 해야할까요????

import React, { useState, useEffect, useRef } from "react";
import { Link } from 'react-router-dom';
import styled from "styled-components";
import Nav from './Nav';

const Images = () => {
  const [data, setData] = useState();
  const [location, setLocation] = useState();
  const scrollBox = useRef(null);

  // 이미지 자료 긁어오기.
  useEffect(()=> {
    fetch(`http://localhost:3000/data/MockupData.json`)
      .then(res => res.json())
      .then(res => {
        setData(res)
      })
      .catch (error => {
        console.log(error);
      });
  }, []);

  //마우스 스크롤 이벤트 작동
  useEffect(() => {
      scrollBox.current.scrollTop();
  }, [location]);

  // const activeOverScrollEvent = () => {
  //   if(window.scrollTop > 400) {
  //     window.scrollTopView(window.scrollTopView(0, 1600))
  //   }
  //   if(window.scrollTop > 1800) {
  //     window.scrollTopView(window.scrollTo(0, 3400))
  //   }
  //   if(window.scrollTop > 3600) {
  //     window.scrollTopView(window.scrollTo(0, 5100))
  //   }
  //   if (window.scrollTop > 5300) {
  //     window.scrollTopView(window.scrollTo(0, 6800))
  //   }
  // };

  return(
    <>
      <Nav />
      <ImagesWrap>
        <ImagesBox>
          {data && data.car.map((el, i)=> {
            console.log(i);
            return (
              <>
                <picture className="images" key={i} ref={scrollBox}>
                  <MiddleBox>
                    <ModelTitle>{el.name}</ModelTitle>
                    <SubTitle>
                      <Link className='subLink' to="">{el.riding}</Link>
                    </SubTitle>
                  </MiddleBox>
                  <UnderBox>
                    <OrderLink>{el.order}</OrderLink>
                    <DetailLink>{el.detail}</DetailLink>
                  </UnderBox>
                  <Imgtag src={el.img_src} alt={el.img_alt} />
                </picture>
              </>
            )
          })
          }
        </ImagesBox>
      </ImagesWrap>
    </>
  )
}

export default Images;

const ImagesWrap = styled.div``; // 최상단 랩핑

const ImagesBox = styled.section``;

const Imgtag = styled.img`
  display: grid;
  width: 1fr;
  height: 1fr;
  max-width: 2048px;
  justify-content: center;
`;

const MiddleBox = styled.div`
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  flex-direction: flex-end;
  align-items: center;
  z-index: 1;
  position: absolute;
  left: 50%;
  margin-top: calc(16vh + 20px);
`;

const ModelTitle = styled.h1`
  display: inline-block;
`;
const SubTitle = styled.h2`
  .subLink {
    
  }
`;

const UnderBox = styled.div`
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: flex-end;
  flex-flow: 1;
`;

const OrderLink = styled(Link)``;
const DetailLink = styled(Link)``;