### HellaJS Reactive Component Examples
Source: https://context7.com/context7/hellajs/llms.txt
Illustrates building reactive components using HellaJS. Components are functions returning JSX elements with reactive bindings. These examples show a simple counter and a form with input validation, demonstrating how signals drive UI updates based on user interactions.
```jsx
import { signal } from '@hellajs/core';
// Simple counter component with reactive updates
const Counter = () => {
const count = signal(0);
return (
Count: {count}
count(count() + 1)}>
Increment
count(count() - 1)}>
Decrement
count(0)}>
Reset
);
};
// Component with multiple reactive values
const UserProfile = () => {
const name = signal('');
const email = signal('');
const isValid = signal(() => name().length > 0 && email().includes('@'));
return (
);
};
```
--------------------------------
### Shared State Management with HellaJS Signals (JavaScript)
Source: https://context7.com/context7/hellajs/llms.txt
Illustrates how to create and use shared state across multiple components using HellaJS signals. This example shows a global store for user authentication, theme switching, and notifications. Requires @hellajs/core.
```javascript
import { signal } from '@hellajs/core';
// Global store
const store = {
user: signal(null),
theme: signal('light'),
notifications: signal([]),
login(userData) {
this.user(userData);
},
logout() {
this.user(null);
},
toggleTheme() {
this.theme(this.theme() === 'light' ? 'dark' : 'light');
},
addNotification(message) {
this.notifications([
...this.notifications(),
{ id: Date.now(), message, timestamp: new Date() }
]);
},
removeNotification(id) {
this.notifications(this.notifications().filter(n => n.id !== id));
}
};
// Components using shared state
const Header = () => {
const user = store.user;
const theme = store.theme;
return (
);
};
const NotificationCenter = () => {
const notifications = store.notifications;
return (
{notifications().map(notif => (
{notif.message}
store.removeNotification(notif.id)}>×
))}
);
};
const App = () => (
store.addNotification('Hello!')}>
Add Notification
);
```
--------------------------------
### List Rendering with HellaJS Signals
Source: https://context7.com/context7/hellajs/llms.txt
Shows how to render dynamic lists in HellaJS using JavaScript array methods and reactive signals. This example includes filtering and updating a list of users, demonstrating reactive updates when the underlying signal changes.
```jsx
import { signal } from '@hellajs/core';
const DataTable = () => {
const users = signal([
{ id: 1, name: 'Alice', role: 'Admin', active: true },
{ id: 2, name: 'Bob', role: 'User', active: true },
{ id: 3, name: 'Charlie', role: 'User', active: false }
]);
const filterRole = signal('all'); // 'all', 'Admin', 'User'
const showInactive = signal(false);
const filteredUsers = signal(() => {
let result = users();
if (filterRole() !== 'all') {
result = result.filter(u => u.role === filterRole());
}
if (!showInactive()) {
result = result.filter(u => u.active);
}
return result;
});
const toggleActive = (id) => {
users(users().map(u =>
u.id === id ? { ...u, active: !u.active } : u
));
};
return (
);
};
```
--------------------------------
### HellaJS Event Handling for Todo App
Source: https://context7.com/context7/hellajs/llms.txt
Shows how to implement event handling and user interactions within a HellaJS component, using a Todo application example. Event handlers update signals, which in turn trigger reactive UI updates for adding, toggling, and removing todos. This demonstrates managing lists of reactive data.
```jsx
import { signal } from '@hellajs/core';
const TodoApp = () => {
const todos = signal([]);
const input = signal('');
const addTodo = () => {
if (input().trim()) {
todos([...todos(), { id: Date.now(), text: input(), done: false }]);
input('');
}
};
const toggleTodo = (id) => {
todos(todos().map(todo =>
todo.id === id ? { ...todo, done: !todo.done } : todo
));
};
const removeTodo = (id) => {
todos(todos().filter(todo => todo.id !== id));
};
return (
);
};
```
--------------------------------
### Conditional Rendering with HellaJS Signals
Source: https://context7.com/context7/hellajs/llms.txt
Illustrates conditional rendering and dynamic content generation in HellaJS based on signal values. This example shows a simple login form and a dashboard that renders different content based on user login status and selected view.
```jsx
import { signal } from '@hellajs/core';
const App = () => {
const isLoggedIn = signal(false);
const username = signal('');
const view = signal('home'); // 'home', 'profile', 'settings'
const LoginForm = () => (
username(e.target.value)}
placeholder="Username"
/>
isLoggedIn(true)}>Login
);
const Dashboard = () => (
Welcome, {username()}!
view('home')}>Home
view('profile')}>Profile
view('settings')}>Settings
{view() === 'home' &&
Home Content
}
{view() === 'profile' &&
Profile Content for {username()}
}
{view() === 'settings' &&
Settings Content
}
{ isLoggedIn(false); username(''); }}>
Logout
);
return (
{isLoggedIn() ? : }
);
};
```
--------------------------------
### Fetch and POST Data with HellaJS Signals (JSX)
Source: https://context7.com/context7/hellajs/llms.txt
Demonstrates using HellaJS signals to manage asynchronous data fetching (GET) and data submission (POST) within a React-like component structure. It handles loading states, errors, and updates the UI reactively. Requires @hellajs/core.
```jsx
import { signal } from '@hellajs/core';
const UsersList = () => {
const users = signal([]);
const loading = signal(false);
const error = signal(null);
const fetchUsers = async () => {
loading(true);
error(null);
try {
const response = await fetch('https://api.example.com/users');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
users(data);
} catch (err) {
error(err.message);
console.error('Failed to fetch users:', err);
} finally {
loading(false);
}
};
// Fetch on component mount
fetchUsers();
return (
Users
Refresh
{loading() &&
Loading...
}
{error() && (
Error: {error()}
Retry
)}
{!loading() && !error() && users().length === 0 && (
No users found
)}
{!loading() && users().length > 0 && (
{users().map(user => (
{user.name} - {user.email}
))}
)}
);
};
// Example with POST request
const CreateUser = () => {
const name = signal('');
const email = signal('');
const submitting = signal(false);
const result = signal(null);
const handleSubmit = async (e) => {
e.preventDefault();
submitting(true);
result(null);
try {
const response = await fetch('https://api.example.com/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: name(),
email: email()
})
});
const data = await response.json();
result({ success: true, data });
name('');
email('');
} catch (err) {
result({ success: false, error: err.message });
} finally {
submitting(false);
}
};
return (
);
};
```
--------------------------------
### HellaJS Signal Creation and Reactivity
Source: https://context7.com/context7/hellajs/llms.txt
Demonstrates how to create and manage reactive signals in HellaJS. Signals are the core of HellaJS's reactivity, automatically tracking dependencies and updating associated computations or UI elements when their values change. They can hold any data type and be used within effects for derived state.
```javascript
import { signal } from '@hellajs/core';
// Create a reactive signal with initial value
const count = signal(0);
// Read the signal value
console.log(count()); // 0
// Update the signal value
count(count() + 1);
console.log(count()); // 1
// Signals can hold any type of data
const user = signal({ name: 'Alice', age: 30 });
user({ name: 'Bob', age: 25 });
// Signals automatically track dependencies in effects
const doubled = signal(() => count() * 2);
console.log(doubled()); // 2
count(5);
console.log(doubled()); // 10
```
--------------------------------
### Computed Values with HellaJS Signals
Source: https://context7.com/context7/hellajs/llms.txt
Demonstrates how HellaJS signals automatically recompute derived values when dependencies change. This is useful for efficient reactive computations without manual tracking. It showcases simple and complex computations with arrays and their updates.
```javascript
import { signal } from '@hellajs/core';
// Computed values update automatically
const firstName = signal('John');
const lastName = signal('Doe');
const fullName = signal(() => `${firstName()} ${lastName()}`);
console.log(fullName()); // "John Doe"
firstName('Jane');
console.log(fullName()); // "Jane Doe"
// Complex computations with multiple dependencies
const items = signal([
{ name: 'Apple', price: 1.5, quantity: 3 },
{ name: 'Banana', price: 0.8, quantity: 5 },
{ name: 'Orange', price: 1.2, quantity: 2 }
]);
const total = signal(() =>
items().reduce((sum, item) => sum + item.price * item.quantity, 0)
);
const itemCount = signal(() =>
items().reduce((sum, item) => sum + item.quantity, 0)
);
const averagePrice = signal(() =>
itemCount() > 0 ? total() / itemCount() : 0
);
console.log(total()); // 11.9
console.log(itemCount()); // 10
console.log(averagePrice()); // 1.19
// Update items and all computed values update automatically
items([...items(), { name: 'Grape', price: 2.0, quantity: 4 }]);
console.log(total()); // 19.9
console.log(itemCount()); // 14
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.