Tooltip On Hover And Focus
ReactJS
Medium
6 views
Problem Description
Build a tooltip that opens on hover and keyboard focus.
Output Format
Render a React component.
Constraints
Use a wrapper and show tooltip on focus/blur too.
Official Solution
import React, { useState } from 'react';
function Tooltip({ text, children }) {
const [open, setOpen] = useState(false);
return (
<span
style={{ position: 'relative', display: 'inline-block' }}
onMouseEnter={() => setOpen(true)}
onMouseLeave={() => setOpen(false)}
onFocus={() => setOpen(true)}
onBlur={() => setOpen(false)}
>
{children}
{open ? (
<span
role='tooltip'
style={{ position: 'absolute', left: '50%', top: 'calc(100% + 8px)', transform: 'translateX(-50%)', background: '#111', color: '#fff', padding: '6px 10px', borderRadius: 10, fontSize: 12, whiteSpace: 'nowrap' }}
>
{text}
</span>
) : null}
</span>
);
}
export default function App() {
return (
<div style={{ padding: 24 }}>
<Tooltip text='Practice small questions on meetcode'>
<button type='button' style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>
Hover me
</button>
</Tooltip>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!