Understanding apex:component in Visualforce

The <apex:component> tag allows you to create custom, reusable Visualforce components. Instead of repeating the same markup across multiple pages, you can define it once as a component and use it wherever needed.


Why Use <apex:component>?

  • Helps keep code DRY (Don’t Repeat Yourself)
  • Promotes modular design for Visualforce pages
  • Easier to maintain and reuse common UI blocks

How to Create a Component

  1. Go to Setup → Visualforce Components
  2. Click New
  3. Define your component like this:
xmlCopyEdit<apex:component>
    <h3>Reusable Header</h3>
    <p>This header can be included on any page.</p>
</apex:component>

Save it as: MyCustomHeader


Using the Component in a Visualforce Page

xmlCopyEdit<apex:page>
    <c:MyCustomHeader />
    <p>Main page content goes here.</p>
</apex:page>

Note: The prefix c: is used for custom components.


Example with Attributes

You can also pass values into a component using <apex:attribute>:

Component:

xmlCopyEdit<apex:component>
    <apex:attribute name="title" type="String" description="Title text" required="true" />
    <h2>{!title}</h2>
</apex:component>

Usage:

xmlCopyEdit<apex:page>
    <c:MyComponent title="Welcome to Job Binge!" />
</apex:page>

Best Practices

  • Keep components focused on a single purpose.
  • Use attributes to make them dynamic and flexible.
  • Use them for headers, footers, alerts, forms, etc.