Props
Passing data to components — required, optional, defaults, and spread
Skills taught: react.props-passing, react.prop-defaults, react.prop-spread, react.props-immutable
Passing and receiving props
// Props are passed as JSX attributes, received as an object
// Destructuring props — the standard approach
function Button({ label, variant = 'primary', disabled = false, onClick }) {
const styles = {
primary: { background: '#4fd1c5', color: '#0e1116' },
secondary: { background: '#e2e8f0', color: '#374151' },
danger: { background: '#ef4444', color: '#fff' },
};
return (
<button
disabled={disabled}
onClick={onClick}
style={{
...styles[variant],
padding: '8px 16px', border: 'none',
borderRadius: '6px', cursor: disabled ? 'not-allowed' : 'pointer',
opacity: disabled ? 0.5 : 1, fontWeight: 'bold'
}}
>
{label}
</button>
);
}
function App() {
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px', display: 'flex', gap: '8px', flexWrap: 'wrap' }}>
<Button label="Save" variant="primary" onClick={() => console.log('Saved!')} />
<Button label="Cancel" variant="secondary" onClick={() => console.log('Cancelled')} />
<Button label="Delete" variant="danger" onClick={() => console.log('Deleted')} />
<Button label="Processing..." disabled />
</div>
);
}
// Prop spreading — forward HTML attributes naturally
function Input({ label, id, error, ...inputProps }) {
// ...inputProps captures all remaining props (type, value, onChange, placeholder, etc.)
return (
<div style={{ marginBottom: '12px' }}>
<label
htmlFor={id}
style={{ display: 'block', fontSize: '0.85rem', marginBottom: '4px', fontWeight: '500' }}
>
{label}
</label>
<input
id={id}
{...inputProps} /* spread: type, value, onChange, placeholder, maxLength... */
style={{
width: '100%', padding: '8px', border: `1px solid ${error ? '#ef4444' : '#d1d5db'}`,
borderRadius: '6px', fontSize: '0.9rem', boxSizing: 'border-box'
}}
/>
{error && <p style={{ color: '#ef4444', fontSize: '0.78rem', margin: '4px 0 0' }}>{error}</p>}
</div>
);
}
function App() {
return (
<div style={{ fontFamily: 'sans-serif', padding: '8px', maxWidth: '300px' }}>
<Input label="Email" id="email" type="email" placeholder="you@example.com" />
<Input label="Age" id="age" type="number" min={0} max={120} error="Must be 18+" />
</div>
);
}
Frequently Asked Questions
What's the difference between props and state?
Props are external data passed into a component from its parent — the component can't change them. State is internal data owned by a component — the component controls it and can change it with setState. Rule of thumb: if data comes from outside the component, it's a prop; if data is managed inside the component, it's state.