stackademic

The leading education platform for anyone with an interest in software development.

Props

Pass data and callbacks from parent to child components

Overview

Props (properties) are read-only inputs to components. Parents pass props down; children use them to render UI or invoke callbacks. Props can be any JavaScript value: strings, numbers, objects, elements, or functions.

Syntax / Usage

function Avatar({ src, alt, size = 48 }) {
  return (
    <img
      src={src}
      alt={alt}
      width={size}
      height={size}
      className="rounded-full"
    />
  )
}

function Profile({ user }) {
  return (
    <div>
      <Avatar src={user.avatarUrl} alt={user.name} />
      <h1>{user.name}</h1>
    </div>
  )
}

// Spread props
function Input(props) {
  return <input className="input" {...props} />
}

// Children as prop
function Panel({ title, children }) {
  return (
    <section>
      <h2>{title}</h2>
      {children}
    </section>
  )
}

Examples

Controlled form field pattern:

function TextField({ label, value, onChange, error }) {
  return (
    <label>
      {label}
      <input value={value} onChange={(e) => onChange(e.target.value)} />
      {error && <span className="error">{error}</span>}
    </label>
  )
}

Render prop (function as child):

function DataLoader({ url, children }) {
  const { data, loading } = useFetch(url)
  return children({ data, loading })
}

Common Mistakes

  • Mutating props inside the child—props are immutable
  • Prop drilling through many layers—use context or composition
  • Passing too many individual props—group related data in an object
  • Spreading unknown props onto DOM elements without filtering event handlers

See Also

components jsx use-state use-context