[React] svg랑 친해지기

서영·2022년 5월 22일
1

React

목록 보기
4/5
post-thumbnail

??? : default로 불러오는거랑 component로 불러오는거랑 머가 다름?😯


🪐 svg 사용하는 방법 두 가지

export { ReactComponent as IcSearch } from './icon_search.svg';
export { default as icPlus } from './icon_plus.svg';
  • svg는 ReactComponent로 사용하거나 default로 불러와서 url 그대로 사용할 수 있다.

🔻 default로 사용

<StIcon src={icPlus} />
  • default로 import한 icPlus는 url이라서 src 속성에 넣어주면 img로 사용할 수 있다.(주영언니가 알려줬다)

🔻 ReactComponent로 사용

const StSearchIcon = styled(IcSearch)`
  position: absolute;
  top: 16px;
  left: 14px;
`;
  • styled-component에서 괄호 안에 컴포넌트를 넣어주면 그 자체로 Component이기 때문에 스타일링이 가능하다.

😯 setState로 svg 이미지를 변경하고 싶어요

솝커톤에서 시간에 따라 아침, 낮, 밤마다 변경되는 3가지 배경화면을 구현해야 했다.

import MorningBackground from "component/common/assets/images/mainBackground_morning.svg";
import DayTimeBackground from "component/common/assets/images/mainBackground_daytime.svg";
import NightBackground from "component/common/assets/images/mainBackground_night.svg";
  • import를 갈겼다.
const [background, setBackground] = useState("");

useEffect(() => {
    onChangeBackgroundByTime();
  }, []);

const onChangeBackgroundByTime = () => {
    const currentTime = new Date().getHours();
    if (currentTime >= 0 && currentTime <= 7) {
      //새벽
      setBackground(NightBackground);
    } else if (currentTime >= 8 && currentTime <= 15) {
      //낮
      setBackground(MorningBackground);
    } else {
      //밤
      setBackground(DayTimeBackground);
    }
  };
  • 24 / 3 = 8시간마다 3개의 배경화면을 각각 보여주고 싶었다.
  • state를 이용해서 화면이 첫 렌더링될 때 currentTime을 체크하고 setState를 통해 state값을 변경했다.
  • 이 때 배경화면은 ReactComponent가 아니라 url 그대로 받아와야 setState가 작동한다.
return (
    <StyledRoot url={background}>
      <StyledMain>{children}</StyledMain>
    </StyledRoot>
  );
  • props로 state를 넘겨줬다.
const StyledRoot = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100vw;
  min-height: 100vh;
  background-image: ${(props) => `url(${props.url})`};
`;
  • background-image 속성에 props를 받아와서 url 설정을 해줬다.
  • 원래 styled-component에서 css를 받아와서 많이 처리하는 편이었는데, 속성 하나만 바꾸는 거면 백틱을 이용해서 이렇게도 쓸 수 있더라.(웹팟짱이 알려줬다)
profile
꾸준히 공부하기

1개의 댓글

comment-user-thumbnail
2022년 6월 12일

이 글 읽고 svg랑 절친 됐어요 👩🏻‍🤝‍👩🏻

답글 달기