Skip to main content

React popover component

  • MouseOver, MouseOut event
  • 改用 Fetch 的方式抓網頁預覽,速度不會差很多
export function PopOver({title, link}){
const [content, setContent] = useState('');
useEffect(() => {
fetch(link)
.then(res => res.text())
.then(text => {
const parser = new DOMParser();
const htmlDocument = parser.parseFromString(text, 'text/html');
const specificContent = htmlDocument.querySelector('.markdown').innerHTML;
setContent(specificContent);
})
.catch(err => setContent(`<h3>${title}</h3>`));
}, []);
return (
<div className='popover'>
{parse(content)}
</div>
)
}

export default function InternalLink({children, link, content}) {
const [isHovered, setIsHovered] = useState(false);

const handleMouseOver = () =>{
setIsHovered(true);
}
const handleMouseOut = () =>{
setIsHovered(false);
}

return (
<div style={{display: 'inline'}} onMouseOver={handleMouseOver} onMouseOut={handleMouseOut}>
<a href={link}className='internal-link'>{children}</a>
{isHovered && <PopOver title={children} link={link}/>}
</div>
);
}
.popover {
display: block;
position: absolute;
z-index: 999;
width: 30rem;
max-height: 20rem;
overflow: hidden;
padding: 1rem;
margin: 1rem;

border-radius: 5px;
color: var(--ifm-color-emphasis-900);
background-color: var(--ifm-color-emphasis-0);
border: 1px solid rgba(0, 0, 0, 0.25);
box-shadow: 6px 6px 36px 0px rgba(0, 0, 0, 0.25);
@media(max-width: 768px) {
display: none;
}
}