React
Beginner
2 min read
Rendering Nothing and Toggling Visibility
Example
import { useState } from 'react';
// null return — component absent from DOM
function Tooltip({ visible, text, children }) {
return (
<span style={{ position: 'relative', display: 'inline-block' }}>
{children}
{visible && (
<span style={{
position: 'absolute', bottom: '130%', left: '50%',
transform: 'translateX(-50%)',
background: '#333', color: '#fff',
padding: '4px 10px', borderRadius: 6,
whiteSpace: 'nowrap', fontSize: 13,
}}>
{text}
</span>
)}
</span>
);
}
// Modal: returning null vs CSS hidden
function Modal({ isOpen, onClose, children }) {
if (!isOpen) return null; // unmount — state inside resets on next open
return (
<div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.5)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
<div style={{ background: '#fff', padding: 32, borderRadius: 12, minWidth: 300 }}>
{children}
<button onClick={onClose} style={{ marginTop: 16 }}>Close</button>
</div>
</div>
);
}
function App() {
const [tip, setTip] = useState(false);
const [open, setOpen] = useState(false);
return (
<div style={{ padding: 32 }}>
<Tooltip visible={tip} text="This is a tooltip!">
<button onMouseEnter={() => setTip(true)} onMouseLeave={() => setTip(false)}>
Hover me
</button>
</Tooltip>
<button onClick={() => setOpen(true)} style={{ marginLeft: 16 }}>
Open modal
</button>
<Modal isOpen={open} onClose={() => setOpen(false)}>
<h2>Hello from Modal</h2>
<p>This content is unmounted when closed.</p>
</Modal>
</div>
);
}
export default App;