Component Registration
The createApp
module provides a component
function for registering custom components. This allows you to create reusable pieces of UI that can be used throughout your application.
Usage
js
const app = createApp({
// ... other app options
});
app.component("my-component", (props) => {
// Component logic here
return <div>My Custom Component</div>;
});
functional way
js
import {createApp} from "//unpkg.com/olova"
const Button = (props) =>{
return(
`
<button">${props.text}</button>
`
)
}
const app = createApp({
template: `
<my-button text="click me!"></my-button>
`
})
app.component("my-button" , Button)
app.mount("#root")
API
component(name, componentFunction)
Registers a new component with the given name and implementation.
Parameters
name
(string): The name of the component. This will be used as the custom element tag in your HTML.componentFunction
(function): A function that returns the component's HTML. It receives aprops
object as its argument.
Returns
- The
component
function doesn't return a value.
Example
Here's an example of how to define and use a custom component:
js
// Define the component
app.component("user-profile", (props) => {
return (
<div class="user-profile">
{" "}
<h2>${props.name}</h2> <p>Email: ${props.email}</p>{" "}
</div>
);
});
// Use the component in your template
const template = (
<div>
{" "}
<h1>User Profiles</h1>{" "}
<user-profile name="John Doe" email="john@example.com"></user-profile>{" "}
<user-profile name="Jane Smith" email="jane@example.com"></user-profile>{" "}
</div>
);
In this example, we've defined a user-profile
component that displays a user's name and email. We can then use this component multiple times in our template, passing different props each time.
Notes
- Component names should be kebab-case in HTML (e.g.,
<user-profile>
), but you can use either kebab-case or camelCase when registering the component ('user-profile'
or'userProfile'
). - The component function should return a string of HTML. This HTML will replace the component tag in the DOM.
- Props are passed to the component as attributes on the component tag and are available in the
props
object in the component function. - Components are processed recursively, so you can use components within other components.
Remember to register all your components before mounting the app to ensure they're available when the template is processed.