테스트를 마치고 나면 사용자의 별점과 등수가 표시되는데, 해당 정보를 트위터와 카카오톡에 공유하는 기능을 만들었다.
트위터 공유
트위터에 공유하기는 굉장히 간편했다. 아래와 같이 url에 공유를 원하는 url 주소를 입력하고, text에 추가로 필요한 텍스트를 입력하면 된다. window.open() 메서드를 버튼 형태로 만들면 해당 코드가 바로 열린다.
https://twitter.com/share?url=url&text=text
<div
className={`${styles["button"]} ${styles["twitter"]}`}
onClick={() => {
window.open(
`https://twitter.com/share?url=https://divdivdiv.com/cinephile&text=나의 시네필 평점은?${starCount}`
);
}}
>
트위터 공유하기
</div>;
카카오톡 공유
카카오톡 공유 기능을 쓰려면 카카오톡에서 제공하는 Kakao.Share 모듈을 활용해야 한다.
declare global {
interface Window {
Kakao: any;
}
}
export default function Page() {
// ...
const onShare = async () => {
await window.Kakao.Share.sendDefault({
objectType: "text",
text: `나의 시네필 평점은? ${starCount}`,
link: {
mobileWebUrl: "https://divdivdiv.com/cinephile",
webUrl: "https://divdivdiv.com/cinephile",
},
});
};
const kakaoInit = () => {
if (!window.Kakao.isInitialized()) window.Kakao.init("???");
};
return (
<div className={styles["container"]}>
// ...
<React.Fragment>
// ...
<div
className={`${styles["button"]} ${styles["kakao"]}`}
onClick={() => {
onShare();
}}
>
카카오톡 공유하기
</div>
// ...
</React.Fragment>
) : (
""
)}
// ...
</div>
<Script src="https://developers.kakao.com/sdk/js/kakao.js" onLoad={kakaoInit} />
</div>
);
}