React
Beginner
1 min read
Destructuring Props and Default Values
Example
// Destructuring with defaults — the idiomatic React style
function Avatar({
src,
alt = 'User avatar',
size = 48,
shape = 'circle', // 'circle' | 'square'
}) {
const radius = shape === 'circle' ? '50%' : '6px';
return (
<img
src={src}
alt={alt}
width={size}
height={size}
style={{ borderRadius: radius, objectFit: 'cover' }}
/>
);
}
// Renaming a prop internally
function Link({ href: url, children, external = false }) {
const extraProps = external ? { target: '_blank', rel: 'noopener noreferrer' } : {};
return <a href={url} {...extraProps}>{children}</a>;
}
// Rest props — forward unknown props to underlying element
function Input({ label, id, ...rest }) {
return (
<div>
<label htmlFor={id}>{label}</label>
<input id={id} {...rest} />
</div>
);
}
// Usage
function App() {
return (
<div>
<Avatar src="/alice.jpg" size={64} />
<Avatar src="/bob.jpg" shape="square" alt="Bob's photo" />
<Link href="https://react.dev" external>React Docs</Link>
<Input label="Email" id="email" type="email" placeholder="you@example.com" />
</div>
);
}
export default App;