How to create and compose React components

· Category: React

Short answer

React components are functions that accept props and return JSX. Composition is achieved by nesting components and passing elements via props or children.

Steps

  1. Define a component as a function.
  2. Accept props as an argument.
  3. Return JSX describing the UI.
  4. Compose by nesting components inside one another or using the children prop.

Example

function Button({ children, onClick }) {
  return <button onClick={onClick}>{children}</button>;
}

function App() {
  return (
    <div>
      <Button onClick={() => alert('Clicked!')}>Submit</Button>
    </div>
  );
}

Tips

  • Keep components small and focused on a single responsibility.
  • Use destructuring in the parameter list for cleaner prop access.
  • Name components with PascalCase so React distinguishes them from HTML tags.