### Install @bedrock-core/ui
Source: https://github.com/bedrock-core/ui/blob/main/packages/ui-runtime/README.md
Installs the main @bedrock-core/ui package, which includes the ui-runtime as a dependency. This is the recommended installation method for most users.
```bash
yarn add @bedrock-core/ui
```
--------------------------------
### Install @bedrock-core/ui-runtime Directly
Source: https://github.com/bedrock-core/ui/blob/main/packages/ui-runtime/README.md
Installs the @bedrock-core/ui-runtime package directly. This is useful if you only need the runtime components and not the entire ui package.
```bash
yarn add @bedrock-core/ui-runtime
```
--------------------------------
### Install Dependencies (npm/yarn)
Source: https://github.com/bedrock-core/ui/blob/main/packages/cli/templates/default/README.md
Installs project dependencies using either npm or yarn package managers. Ensure you have Node.js and a package manager installed.
```bash
npm install
```
```bash
yarn install
```
--------------------------------
### Project Structure Example (TypeScript/React)
Source: https://github.com/bedrock-core/ui/blob/main/packages/cli/templates/default/README.md
Illustrates the directory structure of the Bedrock Core UI project. Highlights key directories like 'packs' (BP/RP), configuration files, and the main entry points.
```tree
├── packs/
│ ├── BP/ # Behavior Pack
│ │ ├── manifest.json
│ │ ├── scripts/
│ │ │ ├── main.ts # Entry point
│ │ │ └── UI/
│ │ │ └── Example.tsx # Example UI component
│ │ └── texts/
│ └── RP/ # Resource Pack
│ ├── manifest.json
│ ├── ui/ # JSON UI decoders (pre-configured)
│ └── texts/
├── config.json # Regolith configuration
├── package.json
├── tsconfig.json
├── eslint.config.mjs
└── core-ui-v*.mcpack
```
--------------------------------
### Install Dependencies and Build Addon with Bedrock Core CLI
Source: https://github.com/bedrock-core/ui/blob/main/packages/cli/README.md
Commands to run after an addon project has been generated by the Bedrock Core CLI. These include installing project dependencies, setting up Regolith filters, building the addon for deployment, and enabling watch mode for live development.
```bash
cd your-addon
yarn install # or npm install
yarn regolith-install # Install Regolith filters
yarn build # Build the addon
yarn watch # Watch for changes and redeploy
```
--------------------------------
### Install Regolith Filters (npm/yarn)
Source: https://github.com/bedrock-core/ui/blob/main/packages/cli/templates/default/README.md
Installs Regolith filters required for the project. This step is crucial for managing and processing configuration and data for Bedrock Edition addons.
```bash
npm run regolith-install
```
```bash
yarn regolith-install
```
--------------------------------
### Serialize UI Properties Example (TypeScript)
Source: https://github.com/bedrock-core/ui/blob/main/packages/ui-runtime/README.md
Demonstrates how to use the `serializeProps` function from `@bedrock-core/ui-runtime` to encode UI properties into a byte format. It shows the expected byte counts for different data types like strings, numbers, and booleans, including the header size.
```typescript
import { serializeProps } from '@bedrock-core/ui-runtime';
const [encoded, bytes] = serializeProps({
type: 'example', // string → 83 bytes
message: 'hello', // string → 83 bytes
count: 123, // number → 27 bytes
ratio: 45.67, // number → 27 bytes
ok: true, // bool → 8 bytes
});
// Total: 83 + 83 + 27 + 27 + 8 = 132 bytes (plus 9-byte header = 141 bytes)
```
--------------------------------
### Watch Mode for Auto-Build (npm/yarn)
Source: https://github.com/bedrock-core/ui/blob/main/packages/cli/templates/default/README.md
Starts the project in watch mode, which automatically rebuilds assets whenever changes are detected in the source files. Useful for active development.
```bash
npm run watch
```
```bash
yarn watch
```
--------------------------------
### CLI - Scaffold New Minecraft Projects (Bash)
Source: https://context7.com/bedrock-core/ui/llms.txt
Command-line tool to scaffold new Minecraft Bedrock addon projects with @bedrock-core/ui pre-configured. Creates project structure, downloads the companion resource pack, and sets up build tooling. This CLI simplifies the initial setup and development environment configuration.
```bash
# Create new project interactively
npx @bedrock-core/ui
# Create with specific name
npx @bedrock-core/ui my-addon
# After project creation, navigate and setup
cd my-addon
yarn install
yarn run regolith-install
yarn run build
# Development workflow
yarn run watch # Watch mode for auto-rebuild
yarn run lint # Lint code
# The CLI downloads the latest .mcpack resource pack automatically
# Double-click the .mcpack file to install it in Minecraft
```
--------------------------------
### Render UI Component Tree with @bedrock-core/ui
Source: https://context7.com/bedrock-core/ui/llms.txt
The `render` function is the primary entry point for displaying a JSX component tree to a player's screen in Minecraft Bedrock. It handles the component tree building, serialization, rendering via the form system, hook effect loop management, and cleanup. This example demonstrates a simple counter UI with state management.
```tsx
import { render, Panel, Text, Button, useState } from '@bedrock-core/ui';
import { world, Player } from '@minecraft/server';
// Define a simple counter component
function CounterUI() {
const [count, setCount] = useState(0);
return (
{`Count: ${count}`}
);
}
// Render when player interacts with something
world.afterEvents.buttonPush.subscribe(({ source, block }) => {
if (source instanceof Player) {
render(CounterUI, source);
}
});
```
--------------------------------
### Create Container UI with Panel Component in @bedrock-core/ui
Source: https://context7.com/bedrock-core/ui/llms.txt
The `Panel` component serves as a foundational layout component for organizing UI elements in the @bedrock-core/ui system. It acts as a container for grouping child elements, utilizing absolute positioning with required width, height, x, and y properties. This example shows a `ProfileCard` using `Panel` and `Image` components.
```tsx
import { Panel, Text, Image } from '@bedrock-core/ui';
function ProfileCard() {
return (
{/* Profile image */}
{/* Player name */}
§l§6Player Name
{/* Description */}
This is a profile description with multiple lines of text.
);
}
```
--------------------------------
### Implement Interactive Buttons with Button Component in @bedrock-core/ui
Source: https://context7.com/bedrock-core/ui/llms.txt
The `Button` component provides interactive functionality for click events within the @bedrock-core/ui framework. The `onPress` callback can be synchronous or asynchronous and triggers UI updates when state changes. This example showcases a `ActionMenu` with buttons for teleporting and receiving items.
```tsx
import { Button, Panel, Text, useState, usePlayer } from '@bedrock-core/ui';
import { world } from '@minecraft/server';
function ActionMenu() {
const [lastAction, setLastAction] = useState('None');
const player = usePlayer();
return (
{`Last Action: ${lastAction}`}
{/* Teleport button */}
{/* Give item button */}
);
}
```
--------------------------------
### Run Bedrock Core CLI Project Scaffolding
Source: https://github.com/bedrock-core/ui/blob/main/packages/cli/README.md
Executes the Bedrock Core CLI to initiate the interactive scaffolding process for a new Minecraft Bedrock addon project. It prompts the user for project details and sets up the necessary files and configurations.
```bash
npx @bedrock-core/cli
```
--------------------------------
### Create a Panel Component
Source: https://github.com/bedrock-core/ui/blob/main/packages/ui-runtime/README.md
Defines a 'Panel' component using the custom JSX runtime. It emphasizes the critical prop order: `withControl` first, then component-specific props with defaults, and finally `children`. Components require absolute positioning props.
```tsx
import { FunctionComponent, JSX } from '@bedrock-core/ui';
import { ControlProps, withControl } from './control';
export interface PanelProps extends ControlProps {
// Component-specific props go here
}
export const Panel: FunctionComponent = ({ children, ...rest }: PanelProps): JSX.Element => ({
type: 'panel',
props: {
...withControl(rest), // Must be first - applies control props in canonical order
// Component-specific props with defaults go here after withControl
children, // Children always last
},
});
```
--------------------------------
### Build Project (npm/yarn)
Source: https://github.com/bedrock-core/ui/blob/main/packages/cli/templates/default/README.md
Builds the project assets, likely compiling TypeScript/React components and preparing them for use in a Minecraft Bedrock Edition addon.
```bash
npm run build
```
```bash
yarn build
```
--------------------------------
### JSON UI Field Binding Template (Decoding)
Source: https://github.com/bedrock-core/ui/blob/main/packages/ui-runtime/README.md
Provides a generic template for JSON UI binding entries used in the decoding process. This template outlines the progressive 'slice → subtract' strategy for extracting raw field values and updating remainders, including placeholders for dynamic width and field names.
```json
{
"binding_type": "view", // full_width
"source_property_name": "('%.{FULL_WIDTH}s' * #rem_after_{PREV})",
"target_property_name": "#raw_{FIELD_NAME}"
},
{
"binding_type": "view",
"source_property_name": "(#rem_after_{PREV} - #raw_{FIELD_NAME})",
"target_property_name": "#rem_after_{FIELD_NAME}"
},
{
"binding_type": "view", // (full_width - marker_width) - prefix_width - padding_char (;)
"source_property_name": "(('%.{FM_WIDTH}s' * #raw_{FIELD_NAME}) - ('%.2s' * #raw_{FIELD_NAME}) - ';')",
"target_property_name": "#{FIELD_NAME}"
}
```
--------------------------------
### Display Formatted Text with @bedrock-core/ui Text Component
Source: https://context7.com/bedrock-core/ui/llms.txt
Renders text content using the `Text` component from `@bedrock-core/ui`. Supports Minecraft formatting codes for styling and dynamic content. Text is limited to 80 characters per field; longer content should use translation keys. Dependencies include `Text` and `Panel` from `@bedrock-core/ui`.
```tsx
import { Text, Panel } from '@bedrock-core/ui';
function FormattedTextExample() {
return (
{/* Bold red title */}
§l§cWarning: Important Message
{/* Regular text with color */}
§7This is a gray text with §agreen§7 and §eYellow§7 highlights
{/* Dynamic text */}
{`Current time: ${new Date().toLocaleTimeString()}`}
);
}
```
--------------------------------
### useEvent Hook - Subscribe to Minecraft Events (React/TS)
Source: https://context7.com/bedrock-core/ui/llms.txt
Subscribes to Minecraft event signals with automatic cleanup. The subscription updates when dependencies change and unsubscribes on unmount. Supports optional subscription options like blockTypes or event filters. This hook is useful for tracking game events and updating the UI in real-time.
```tsx
import { useEvent, useState, Panel, Text, usePlayer } from '@bedrock-core/ui';
import { world } from '@minecraft/server';
function BlockBreakTracker() {
const [blocksBreken, setBlocksBroken] = useState(0);
const [lastBlock, setLastBlock] = useState('None');
const player = usePlayer();
// Subscribe to block break events
useEvent(
world.afterEvents.playerBreakBlock,
(event) => {
// Only track events for current player
if (event.player.id === player.id) {
setBlocksBroken(prev => prev + 1);
setLastBlock(event.brokenBlockPermutation.type.id);
}
},
undefined, // No options needed
[player.id] // Resubscribe if player changes
);
return (
§l§eBlock Break Statistics
{`Total Broken: ${blocksBreken}`}
{`Last Block: ${lastBlock.replace('minecraft:', '')}`}
);
}
```
--------------------------------
### useExit Hook - Programmatically Close UI (React/TS)
Source: https://context7.com/bedrock-core/ui/llms.txt
Returns a function to programmatically close the UI. When called, triggers cleanup of all effects and unmounts the component tree. Useful for implementing custom close buttons or conditional UI dismissal. This hook ensures proper cleanup and unmounting of UI components.
```tsx
import { useExit, useEffect, useState, Panel, Button, Text } from '@bedrock-core/ui';
function AutoCloseDialog() {
const exit = useExit();
const [countdown, setCountdown] = useState(5);
// Auto-close after countdown
useEffect(() => {
if (countdown <= 0) {
exit();
return;
}
const timer = setTimeout(() => {
setCountdown(countdown - 1);
}, 1000);
return () => clearTimeout(timer);
}, [countdown, exit]);
return (
§l§cWarning Message
This will close in {countdown} seconds
);
}
```
--------------------------------
### Display Textures with @bedrock-core/ui Image Component
Source: https://context7.com/bedrock-core/ui/llms.txt
Renders texture images from the resource pack using the `Image` component from `@bedrock-core/ui`. Texture paths are relative to the resource pack root, excluding the file extension. Dependencies include `Image`, `Panel`, and `Text` from `@bedrock-core/ui`.
```tsx
import { Image, Panel, Text } from '@bedrock-core/ui';
function IconGrid() {
return (
§lItem Icons
{/* Diamond icon */}
{/* Gold ingot icon */}
{/* Custom texture */}
);
}
```
--------------------------------
### Create Context with createContext (React)
Source: https://context7.com/bedrock-core/ui/llms.txt
The `createContext` function creates a Context object, enabling data sharing throughout the component tree without prop drilling. It returns a Context object with a Provider component and a default value, used when no Provider is found in the tree.
```tsx
import { createContext, useContext, useState, Panel, Text } from '@bedrock-core/ui';
// Define types for better type safety
interface Settings {
volume: number;
showNotifications: boolean;
}
// Create typed context
const SettingsContext = createContext({
volume: 50,
showNotifications: true
});
function VolumeDisplay() {
const settings = useContext(SettingsContext);
return (
{`Volume: ${settings.volume}%`}
);
}
function NotificationStatus() {
const settings = useContext(SettingsContext);
return (
{`Notifications: ${settings.showNotifications ? 'On' : 'Off'}`}
);
}
function SettingsPanel() {
const [settings, setSettings] = useState({
volume: 75,
showNotifications: false
});
return (
);
}
```
--------------------------------
### Access Current Player with usePlayer (React)
Source: https://context7.com/bedrock-core/ui/llms.txt
The `usePlayer` hook provides access to the Player instance associated with the current render session. This allows components to interact directly with the player, enabling player-specific operations and UI updates.
```tsx
import { usePlayer, Panel, Text, Button } from '@bedrock-core/ui';
function PlayerInfo() {
const player = usePlayer();
return (
§l§6Player Information
{`Name: ${player.name}`}
{`Health: ${player.getComponent('health')?.currentValue ?? 0}`}
);
}
```
--------------------------------
### State Management with @bedrock-core/ui useState Hook
Source: https://context7.com/bedrock-core/ui/llms.txt
Provides React-like state management with the `useState` hook from `@bedrock-core/ui`. It persists values across renders, and the setter function supports direct values or updater functions. State updates trigger component re-renders. Dependencies include `useState`, `Panel`, `Button`, and `Text` from `@bedrock-core/ui`.
```tsx
import { useState, Panel, Button, Text } from '@bedrock-core/ui';
function TodoCounter() {
// Initialize state with a value
const [todos, setTodos] = useState(['Task 1', 'Task 2']);
const [completed, setCompleted] = useState(0);
return (
{`Total: ${todos.length} | Completed: ${completed}`}
);
}
```
--------------------------------
### Side Effects with @bedrock-core/ui useEffect Hook
Source: https://context7.com/bedrock-core/ui/llms.txt
Handles side effects after render commits using the `useEffect` hook from `@bedrock-core/ui`. It supports dependency arrays for conditional execution and cleanup functions for unmounting or re-running effects. Essential for integrating with Minecraft APIs like subscriptions or intervals. Dependencies include `useEffect`, `useState`, `Panel`, `Text`, `useRef` from `@bedrock-core/ui` and `system` from `@minecraft/server`.
```tsx
import { useEffect, useState, Panel, Text, useRef } from '@bedrock-core/ui';
import { system } from '@minecraft/server';
function AutoTimer() {
const [seconds, setSeconds] = useState(0);
const [isRunning, setIsRunning] = useState(false);
const intervalRef = useRef(undefined);
// Effect with cleanup for interval management
useEffect(() => {
if (!isRunning) {
return;
}
// Start interval (20 ticks = 1 second)
intervalRef.current = system.runInterval(() => {
setSeconds(prev => prev + 1);
}, 20);
// Cleanup function - runs on unmount or when effect re-runs
return () => {
if (intervalRef.current !== undefined) {
system.clearRun(intervalRef.current);
intervalRef.current = undefined;
}
};
}, [isRunning]); // Re-run when isRunning changes
// Effect that runs only once on mount
useEffect(() => {
console.log('Timer component mounted');
return () => {
console.log('Timer component unmounted');
};
}, []); // Empty deps = run once
return (
{`Time: ${seconds}s`}
{`Status: ${isRunning ? 'Running' : 'Stopped'}`}
);
}
```
--------------------------------
### Consume Context Value with useContext (React)
Source: https://context7.com/bedrock-core/ui/llms.txt
The `useContext` hook consumes context values from the nearest Provider ancestor. It returns the context's default value if no Provider is found. This hook is crucial for sharing state across components without prop drilling.
```tsx
import { createContext, useContext, useState, Panel, Text, Button } from '@bedrock-core/ui';
// Create context with default value
const ThemeContext = createContext<'light' | 'dark'>('light');
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
);
}
function ThemeProvider() {
const [theme, setTheme] = useState<'light' | 'dark'>('light');
return (
);
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.