### Quick Start: Scaffold a New Addon with CLI
Source: https://bedrock-core.drav.dev/docs/ui/get-started/installation
Use the CLI tool to quickly set up a new Minecraft Bedrock addon project with @bedrock-core/ui pre-configured, including TypeScript, ESLint, Regolith, and a companion resource pack. This is the recommended method for new projects.
```bash
npx @bedrock-core/ui
cd your-addon-name
yarn install # or npm install
yarn regolith-install # Install Regolith filters
yarn build # Build the addon
yarn watch # Watch for changes and redeploy
```
--------------------------------
### Basic Panel Example
Source: https://bedrock-core.drav.dev/docs/ui/components/Panel
A simple example showcasing a Panel with defined dimensions and internal text content. This illustrates the basic structure and how to set width and height properties.
```javascript
Simple panel content
```
--------------------------------
### Manual Installation: Add Package to Existing Project
Source: https://bedrock-core.drav.dev/docs/ui/get-started/installation
Install the @bedrock-core/ui package into an existing project using Yarn or npm. This method is suitable for integrating the UI library into a project that is already set up.
```bash
yarn add @bedrock-core/ui
```
--------------------------------
### Manual Installation: Add Companion Resource Pack Dependency
Source: https://bedrock-core.drav.dev/docs/ui/get-started/installation
Manually add the companion resource pack as a dependency in your behavior pack's `manifest.json` file. This ensures the resource pack is correctly linked to your behavior pack.
```json
{
"dependencies": [
{
"uuid": "761ecd37-ad1c-4a64-862a-d6cc38767426",
"version": [x, y, z]
}
]
}
```
--------------------------------
### Quick Test: Render a Simple UI Component
Source: https://bedrock-core.drav.dev/docs/ui/get-started/installation
Test your installation by rendering a simple 'Hello World' UI component in Minecraft Bedrock using the provided JavaScript code. This snippet demonstrates how to import and use components from `@bedrock-core/ui` and interact with Minecraft's world events.
```typescript
import { render, Panel, Text } from '@bedrock-core/ui';
import { world, Player, Entity, ButtonPushAfterEvent } from '@minecraft/server';
import { MinecraftEntityTypes } from '@minecraft/vanilla-data';
const HelloWorld = (
Hello from @bedrock-core/ui!
);
const isPlayer = (source: Entity): source is Player => source.typeId === MinecraftEntityTypes.Player;
world.afterEvents.buttonPush.subscribe(({ source }: ButtonPushAfterEvent): void => {
if (isPlayer(source)) {
render(HelloWorld, source);
}
});
```
--------------------------------
### Basic Positioning Example - JSX
Source: https://bedrock-core.drav.dev/docs/ui/components/control-props
Demonstrates how to set the position and dimensions of a Text component using x, y, width, and height props. This is a fundamental example for layout control.
```jsx
Positioned text
```
--------------------------------
### Image Gallery Example
Source: https://bedrock-core.drav.dev/docs/ui/components/Image
Illustrates how to create an image gallery by mapping an array of texture paths to multiple Image components. This example shows dynamic rendering of multiple images within a container.
```javascript
function ImageGallery() {
const images = [
'textures/items/diamond',
'textures/items/gold_ingot',
'textures/items/iron_ingot',
'textures/items/emerald'
];
return (
{images.map((texture, index) => (
))}
);
}
```
--------------------------------
### useEffect: Run Once on Mount Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEffect
Shows how to use useEffect with an empty dependency array to execute an effect only once after the initial render (component mount). This is common for initial data fetching or setup.
```javascript
function DataLoader() {
const [data, setData] = useState(null);
useEffect(() => {
console.log('Component mounted, loading data...');
// Load data logic here
setData('Loaded data');
}, []); // Empty array = run once
return {data || 'Loading...'};
}
```
--------------------------------
### Player Join Notification Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEvent
An example showcasing how to use the useEvent hook to display a list of the last 5 players who joined the game. It manages a state array to keep track of recent players.
```javascript
import { world } from '@minecraft/server';
import { useEvent } from '@bedrock-core/ui';
import { useState } from 'react'; // Assuming useState is available
import { Panel, Text } from './ui'; // Assuming Panel and Text components exist
function PlayerJoinNotification() {
const [recentPlayers, setRecentPlayers] = useState([]);
useEvent(
world.afterEvents.playerJoin,
(event) => {
setRecentPlayers(prev => [...prev, event.playerName].slice(-5));
}
);
return (
Recent Joins
{recentPlayers.map((name, index) => (
{name}
))}
);
}
```
--------------------------------
### Best Practice: Managing Dependencies Correctly
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEvent
Provides examples of correctly managing the dependency array for the useEvent hook. It shows when to include dependencies used within the callback and when they are not necessary.
```javascript
// ✅ Good - include dependencies used inside the callback
function EventHandler() {
const player = usePlayer(); // Assuming usePlayer hook exists
useEvent(
world.afterEvents.entityHealthChanged,
(event) => {
// Using player inside - add to deps
if (event.entity.id === player.id) {
handleHealthChange(event); // Assuming handleHealthChange exists
}
},
undefined,
[player]
);
}
// ✅ Good - no external dependencies needed
function EventHandler() {
useEvent(
world.afterEvents.playerJoin,
(event) => {
// No external dependencies used
console.log(`${event.playerName} joined`);
}
// deps not needed
);
}
```
--------------------------------
### useEffect: Timer/Interval Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEffect
Provides an example of using useEffect to manage a countdown timer. It utilizes `system.runInterval` from '@minecraft/server' and includes a cleanup function to stop the interval when the component unmounts or the condition is met.
```javascript
import { system } from '@minecraft/server';
function Countdown() {
const [timeLeft, setTimeLeft] = useState(60);
useEffect(() => {
if (timeLeft <= 0) return;
const runId = system.runInterval(() => {
setTimeLeft(timeLeft - 1);
}, 20); // Runs every 20 ticks (1 second)
return () => system.clearRun(runId);
}, [timeLeft]);
return (
{`Time Left: ${timeLeft}s`}
);
}
```
--------------------------------
### Basic Close Button Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useExit
A straightforward example of a button that calls the exit function provided by the useExit hook directly on press. This is useful for simple UI close actions.
```javascript
function CloseUI() {
const exit = useExit();
return (
);
}
```
--------------------------------
### useEffect Usage Example with Timer
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEffect
Demonstrates using useEffect to set up and clean up a timer interval using '@minecraft/server'. The effect runs once on mount and clears the interval when the component unmounts.
```javascript
import { system } from '@minecraft/server';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const runId = system.runInterval(() => {
setSeconds(s => s + 1);
}, 20); // Runs every 20 ticks (1 second)
// Cleanup function
return () => system.clearRun(runId);
}, []); // Empty deps = run once on mount
return {`Time: ${seconds}s`};
}
```
--------------------------------
### Nested Panel Structure Example
Source: https://bedrock-core.drav.dev/docs/ui/components/Panel
Illustrates how to create nested Panel components. This example shows a main Panel containing two child Panels, each with their own content and positioning. The coordinates (x, y) and dimensions are relative to their parent Panel.
```javascript
Nested Panel HeaderNested Panel Content
```
--------------------------------
### Provide Meaningful Defaults for Context
Source: https://bedrock-core.drav.dev/docs/ui/api/createContext
This example illustrates the best practice of providing meaningful default values when creating a context. A good default makes the context usable even before a provider is set up.
```typescript
// ✅ Good - meaningful default values
const ThemeContext = createContext({
color: '#000000',
fontSize: 14
});
// ❌ Less ideal
const ThemeContext = createContext(null);
```
--------------------------------
### useEffect: Fetch Data on Mount Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEffect
Demonstrates fetching data when a component mounts using useEffect. It simulates an asynchronous data fetch with `setTimeout` and shows a loading state before displaying the fetched data.
```javascript
function PlayerStats() {
const [stats, setStats] = useState(null);
const [loading, setLoading] = useState(true);
const player = usePlayer();
useEffect(() => {
// Simulate async data fetch
setLoading(true);
setTimeout(() => {
setStats({
health: player.health,
level: player.level
});
setLoading(false);
}, 1000);
}, []); // Load once on mount
if (loading) {
return Loading stats...;
}
return (
<>
{`Health: ${stats?.health}`}{`Level: ${stats?.level}`}
>
);
}
```
--------------------------------
### Texture Path Format Example
Source: https://bedrock-core.drav.dev/docs/ui/components/Image
Illustrates the correct format for specifying texture paths. Paths should be relative to the Resource Pack root, use forward slashes, and omit file extensions. This ensures correct loading of image resources.
```plaintext
packs/RP/
└── textures/
└── ui/
├── icons/
│ ├── health.png
│ └── mana.png
└── backgrounds/
└── panel_bg.png
Usage:
```
--------------------------------
### Button Component API
Source: https://bedrock-core.drav.dev/docs/ui/components/Button
Documentation for the Button component, including its props and usage examples.
```APIDOC
## Button Component
Interactive button component that responds to player interactions.
### Import
```javascript
import { Button } from '@bedrock-core/ui';
```
### Usage
```javascript
```
### Props
#### Component-Specific Props
- **onPress** (function) - Callback function executed when button is pressed. Default: `undefined`
- **children** (JSX.Node) - Child components (typically a Text component). Required: No
#### Control Props
Button inherits all standard control props.
### Examples
#### Basic Button
```javascript
```
#### Button with State
```javascript
function ToggleButton() {
const [isActive, setIsActive] = useState(false);
return (
);
}
```
#### Disabled Button
```javascript
```
### Best Practices
- Space buttons adequately to prevent accidental clicks
- Use descriptive button labels that clearly indicate the action
- Disable buttons when actions are unavailable rather than hiding them
```
--------------------------------
### Multiple Event Listeners Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEvent
Illustrates how to attach multiple useEvent listeners to different events (player join and player leave) within the same component. It maintains a log of recent events.
```javascript
import { world } from '@minecraft/server';
import { useEvent } from '@bedrock-core/ui';
import { useState } from 'react'; // Assuming useState is available
import { Panel, Text } from './ui'; // Assuming Panel and Text components exist
function MultiEventTracker() {
const [eventLog, setEventLog] = useState([]);
useEvent(
world.afterEvents.playerJoin,
(event) => {
setEventLog(prev => [...prev, `${event.playerName} joined`].slice(-5));
}
);
useEvent(
world.afterEvents.playerLeave,
(event) => {
setEventLog(prev => [...prev, `${event.playerName} left`].slice(-5));
}
);
return (
Event Log
{eventLog.map((log, index) => (
{log}
))}
);
}
```
--------------------------------
### Basic Event Listener Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEvent
Demonstrates a basic usage of the useEvent hook to listen for player join events and update a UI text element with the player's name. It imports necessary components from '@minecraft/server' and '@bedrock-core/ui'.
```javascript
import { world } from '@minecraft/server';
import { useEvent } from '@bedrock-core/ui';
import { useState } from 'react'; // Assuming useState is available
import { Text } from './ui'; // Assuming Text component exists
function EventListener() {
const [lastEvent, setLastEvent] = useState('None');
useEvent(
world.afterEvents.playerJoin,
(event) => {
setLastEvent(event.playerName);
}
);
return (
{`Last event: ${lastEvent}`}
);
}
```
--------------------------------
### Positioning Modes Example - JSX
Source: https://bedrock-core.drav.dev/docs/ui/components/control-props
Demonstrates the difference between 'relative' and 'absolute' positioning for Text components within a Panel. 'Relative' positions elements from the parent's origin, while 'absolute' positions from the screen origin.
```jsx
<>
{/* Relative positioning - positioned from parent origin */}
Relative position
{/* Absolute positioning - positioned from screen origin */}
Absolute position
>
```
--------------------------------
### Render UI component to player - TypeScript Example
Source: https://bedrock-core.drav.dev/docs/ui/api/render
Demonstrates how to use the 'render' function to display a UI. It includes importing necessary components, defining a simple UI structure with 'Panel' and 'Text', and rendering it to a player when a button is pushed. Requires '@bedrock-core/ui' and '@minecraft/server' libraries.
```typescript
import { render, Panel, Text } from '@bedrock-core/ui';
import { world } from '@minecraft/server';
function WelcomeScreen() {
return (
Hello, Minecraft!
);
}
const isPlayer = (source: Entity): source is Player => source.typeId === MinecraftEntityTypes.Player;
// Render it to a player
world.afterEvents.buttonPush.subscribe(({ source }: ButtonPushAfterEvent): void => {
if (isPlayer(source)) {
render(, source);
}
});
```
--------------------------------
### Import Panel Component from @bedrock-core/ui
Source: https://bedrock-core.drav.dev/docs/ui/components/Panel
This snippet shows how to import the Panel component from the @bedrock-core/ui library. Ensure the library is installed in your project.
```javascript
import { Panel } from '@bedrock-core/ui';
```
--------------------------------
### Item Use Counter Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEvent
This example demonstrates using the useEvent hook to track the number of times an item has been used and display the ID of the last item used. It utilizes two state variables to store the count and the last item's ID.
```javascript
import { world } from '@minecraft/server';
import { useEvent } from '@bedrock-core/ui';
import { useState } from 'react'; // Assuming useState is available
import { Text } from './ui'; // Assuming Text component exists
function ItemUseTracker() {
const [useCount, setUseCount] = useState(0);
const [lastItem, setLastItem] = useState('None');
useEvent(
world.afterEvents.itemUse,
(event) => {
setUseCount(prev => prev + 1);
setLastItem(event.itemStack.typeId);
}
);
return (
<>
{`Item uses: ${useCount}`}{`Last used: ${lastItem}`}
>
);
}
```
--------------------------------
### TypeScript Configuration for JSX Support
Source: https://bedrock-core.drav.dev/docs/ui/get-started/installation
Configure your `tsconfig.json` file to enable JSX support with `@bedrock-core/ui` by setting the `jsx` option to `react-jsx` and specifying the `jsxImportSource`. This allows you to use JSX syntax in your TypeScript files.
```json
{
"compilerOptions": {
"jsx": "react-jsx",
"jsxImportSource": "@bedrock-core/ui"
}
}
```
--------------------------------
### useEffect: Cleanup Function Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEffect
Demonstrates the cleanup functionality of useEffect. It shows how to schedule a timeout using '@minecraft/server' and then clear that timeout when the component unmounts to prevent memory leaks.
```javascript
import { system } from '@minecraft/server';
function EventListener() {
useEffect(() => {
const runId = system.runTimeout(() => {
console.log('Timeout executed');
}, 100); // Execute after 100 ticks (~5 seconds)
// Cleanup: cancel timeout when component unmounts
return () => {
system.clearRun(runId);
};
}, []);
return Timeout scheduled...;
}
```
--------------------------------
### useEffect: Multiple Effects Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEffect
Illustrates how to define multiple independent useEffect hooks within a single component. Each effect can manage its own side effect and dependencies, leading to more organized code.
```javascript
function MultiEffect() {
const [count, setCount] = useState(0);
const [name, setName] = useState('Player');
// Effect 1: Log count changes
useEffect(() => {
console.log(`Count changed to: ${count}`);
}, [count]);
// Effect 2: Log name changes
useEffect(() => {
console.log(`Name changed to: ${name}`);
}, [name]);
// Effect 3: Run on every execution
useEffect(() => {
console.log('Component executed');
});
return (
<>
{`Count: ${count}`}{`Name: ${name}`}
>
);
}
```
--------------------------------
### Disabled Button Example
Source: https://bedrock-core.drav.dev/docs/ui/components/Button
Demonstrates how to create a disabled Button component. The `enabled` prop is set to `false` to prevent user interaction, indicated by the 'Disabled' label.
```jsx
```
--------------------------------
### Timer Example with useRef
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useRef
Demonstrates using useRef to store and manage the ID of a system interval in a Timer component. This allows the interval to be cleared later using system.clearRun. It utilizes @minecraft/server and @bedrock-core/ui components.
```typescript
import { system } from '@minecraft/server';
function Timer() {
const intervalRef = useRef(null);
const [count, setCount] = useState(0);
const startTimer = () => {
intervalRef.current = system.runInterval(() => {
setCount(c => c + 1);
}, 20); // Runs every 20 ticks (1 second)
};
const stopTimer = () => {
if (intervalRef.current !== null) {
system.clearRun(intervalRef.current);
intervalRef.current = null;
}
};
return (
<>
{`Count: ${count}`}
>
);
}
```
--------------------------------
### useState Hook Signature and Usage
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useState
Demonstrates the signature of the useState hook, which accepts an initial state value and returns the current state and a setter function. The usage example shows a basic counter component.
```javascript
function useState(initial: T | (() => T)): [T, (value: T | ((prev: T) => T)) => void]
function Counter() {
const [count, setCount] = useState(0);
return (
<>
{`Count: ${count}`}
>
);
}
```
--------------------------------
### Example: User Context for Authentication State
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useContext
Shows how to use useContext to access user information, such as ID, name, and role, from a UserContext. This is useful for displaying user-specific data or controlling access based on roles.
```typescript
interface User {
id: string;
name: string;
role: 'admin' | 'user';
}
const UserContext = createContext(null);
function App() {
const currentUser: User = {
id: '123',
name: 'Steve',
role: 'admin'
};
return (
);
}
function Dashboard() {
const user = useContext(UserContext);
if (!user) {
return Not logged in;
}
return (
{`Welcome, ${user.name}!`}{`Role: ${user.role}`}
);
}
```
--------------------------------
### Visibility Control Example - React (JSX)
Source: https://bedrock-core.drav.dev/docs/ui/components/control-props
Illustrates controlling the visibility of a Button component based on a state variable 'showButton' using the 'visible' prop. This is useful for dynamic UI elements.
```jsx
function ConditionalUI({ showButton }) {
return (
<>
Some text
>
);
}
```
--------------------------------
### Array State Management with useState Hook
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useState
Illustrates managing an array as state using the useState hook. This example implements a simple todo list where new tasks can be added and the last one removed.
```javascript
function TodoList() {
const [todos, setTodos] = useState(['First task']);
const addTodo = () => {
setTodos([...todos, `Task ${todos.length + 1}`]);
};
const removeLast = () => {
setTodos(todos.slice(0, -1));
};
return (
{todos.map((todo, index) => (
{`${index + 1}. ${todo}`}
))}
);
}
```
--------------------------------
### Clickable Image Button Example
Source: https://bedrock-core.drav.dev/docs/ui/components/Image
Shows how to use the Image component as a visual element within a Button component. The Image is a child of the Button, allowing it to be interactive and respond to press events.
```javascript
function ImageButton() {
return (
);
}
```
--------------------------------
### useEffect: Run on State Change Example
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEffect
Illustrates using useEffect with a dependency array containing a state variable. The effect will re-run whenever the specified state variable changes, useful for reacting to user input or data updates.
```javascript
function SearchResults() {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
useEffect(() => {
if (query.length > 0) {
console.log(`Searching for: ${query}`);
// Perform search
setResults([`Result for ${query}`]);
}
}, [query]); // Runs when query changes
return (
<>
{`Search: ${query}`}
{results.map((result, i) => (
{result}
))}
>
);
}
```
--------------------------------
### Dynamic Content Grouping with Fragment in React
Source: https://bedrock-core.drav.dev/docs/ui/components/Fragment
Provides an example of using Fragment for dynamic content grouping based on a boolean prop (`isOnline`). This allows rendering different sets of sibling elements depending on the state, without adding extra DOM wrappers.
```javascript
function StatusDisplay({ isOnline }) {
return (
<>
Status:
{isOnline ? (
<>
§2OnlineConnected users: 5
>
) : (
<>
§cOfflineReconnecting...
>
)}
>
);
}
```
--------------------------------
### Todo List Component with useReducer
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useReducer
A comprehensive example demonstrating the use of useReducer to manage a todo list. It includes state management for todos and the next available ID, along with actions for adding, toggling, deleting, and clearing todos.
```typescript
interface Todo {
id: number;
text: string;
completed: boolean;
}
interface State {
todos: Todo[];
nextId: number;
}
type Action =
| { type: 'add'; text: string }
| { type: 'toggle'; id: number }
| { type: 'delete'; id: number }
| { type: 'clear' };
function todoReducer(state: State, action: Action): State {
switch (action.type) {
case 'add':
return {
...state,
todos: [...state.todos, { id: state.nextId, text: action.text, completed: false }],
nextId: state.nextId + 1
};
case 'toggle':
return {
...state,
todos: state.todos.map(todo =>
todo.id === action.id ? { ...todo, completed: !todo.completed } : todo
)
};
case 'delete':
return {
...state,
todos: state.todos.filter(todo => todo.id !== action.id)
};
case 'clear':
return { todos: [], nextId: 1 };
default:
return state;
}
}
function TodoApp() {
const [state, dispatch] = useReducer(todoReducer, { todos: [], nextId: 1 });
return (
{state.todos.map((todo, index) => (
{`${todo.completed ? '✓' : '○'} ${todo.text}`}
))}
);
}
```
--------------------------------
### Structure Complex Logic with Helper Functions (TypeScript)
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useReducer
Demonstrates how to manage complex application logic by breaking it down into smaller, reusable helper functions. This example shows an `addItem` function and how it's used within a `reducer` function for better organization and testability.
```typescript
// ✅ Good - helper functions
function addItem(state: State, item: Item): State {
const existingItem = state.items.find(i => i.id === item.id);
if (existingItem) {
return updateItemQuantity(state, item.id, existingItem.quantity + 1);
}
return { ...state, items: [...state.items, item] };
}
function reducer(state: State, action: Action): State {
switch (action.type) {
case 'addItem':
return addItem(state, action.item);
// ...
}
}
```
--------------------------------
### Conditional UI based on Admin Permissions
Source: https://bedrock-core.drav.dev/docs/ui/hooks/usePlayer
This example shows how to use the usePlayer hook to check a player's command permission level and conditionally render UI elements. It displays an 'Access Denied' message for non-admin users and an 'Admin Panel' for admins.
```javascript
function AdminPanel() {
const player = usePlayer();
const isAdmin = player.commandPermissionLevel === CommandPermissionLevel.Admin;
if (!isAdmin) {
return (
Access Denied
);
}
return (
Admin Panel
);
}
```
--------------------------------
### React: Dependent useEffect Hooks
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useEffect
Demonstrates how to manage dependent side effects in React using useEffect. This example shows loading user data based on a userId, and then loading posts based on the loaded user data. It utilizes the useState and useEffect hooks.
```javascript
function DependentEffects() {
const [userId, setUserId] = useState(1);
const [user, setUser] = useState(null);
const [posts, setPosts] = useState([]);
// Effect 1: Load user when userId changes
useEffect(() => {
console.log(`Loading user ${userId}...`);
// Fetch user data
setUser({ id: userId, name: `User ${userId}` });
}, [userId]);
// Effect 2: Load posts when user changes
useEffect(() => {
if (user) {
console.log(`Loading posts for ${user.name}...`);
// Fetch posts
setPosts([`Post 1 by ${user.name}`]);
}
}, [user]);
return (
<>
{user?.name || 'Loading...'}
{posts.map((post, i) => (
{post}
))}
>
);
}
```
--------------------------------
### Image Component Best Practices
Source: https://bedrock-core.drav.dev/docs/ui/components/Image
Provides recommendations for optimizing image usage, including texture slicing, file size management, organization, and dimension matching.
```APIDOC
## Best Practices for Image Component
### Description
Recommendations for using the Image component effectively to ensure optimal performance, visual quality, and pack size.
### Practices
- **Nine-Sliced Textures**: Prefer using nine-sliced textures when scaling images to maintain quality.
- **File Size**: Keep texture file sizes small to minimize the overall size of your resource pack.
- **Organization**: Organize textures logically within `textures/ui/` folders for better maintainability.
- **Dimension Matching**: Ensure texture dimensions match your UI layout precisely for crisp rendering.
```
--------------------------------
### Create a Theme Context using createContext
Source: https://bedrock-core.drav.dev/docs/ui/api/createContext
Demonstrates how to create a ThemeContext using createContext with specific default values for primaryColor and backgroundColor. This context can then be provided to child components.
```typescript
interface Theme {
primaryColor: string;
backgroundColor: string;
}
const ThemeContext = createContext({
primaryColor: '#ffffff',
backgroundColor: '#000000'
});
function App() {
return (
);
}
function ThemedText() {
const theme = useContext(ThemeContext);
return (
{`Primary: ${theme.primaryColor}`}
);
}
function ThemedButton() {
const theme = useContext(ThemeContext);
return (
);
}
```
--------------------------------
### Create a Settings Context with Updates using createContext
Source: https://bedrock-core.drav.dev/docs/ui/api/createContext
Shows how to create a SettingsContext that holds both the current settings and a function to update them. This enables components to modify application settings like volume and brightness.
```typescript
interface Settings {
volume: number;
brightness: number;
}
interface SettingsContextValue {
settings: Settings;
updateSettings: (partial: Partial) => void;
}
const SettingsContext = createContext({
settings: { volume: 50, brightness: 80 },
updateSettings: () => {}
});
function SettingsProvider({ children }: { children: JSX.Element }) {
const [settings, setSettings] = useState({
volume: 50,
brightness: 80
});
const updateSettings = (partial: Partial) => {
setSettings(prev => ({ ...prev, ...partial }));
};
return (
{children}
);
}
function VolumeControl() {
const { settings, updateSettings } = useContext(SettingsContext);
return (
<>
{`Volume: ${settings.volume}%`}
>
);
}
```
--------------------------------
### Basic Panel Usage with Content
Source: https://bedrock-core.drav.dev/docs/ui/components/Panel
Demonstrates the fundamental usage of the Panel component with specified width and height, containing a Text element. The Text element's position and size are relative to the panel's dimensions.
```javascript
function Example() {
return (
Content inside panel
);
}
```
--------------------------------
### Conditional UI Close
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useExit
Shows how to conditionally call the exit function based on the application's state. In this example, the UI only closes if a 'isSaved' state is true, preventing accidental exits.
```javascript
function ConditionalClose() {
const exit = useExit();
const [isSaved, setIsSaved] = useState(false);
return (
<>
{`Saved: ${isSaved ? 'Yes' : 'No'}`}
>
);
}
```
--------------------------------
### Texture Path Format Guidelines
Source: https://bedrock-core.drav.dev/docs/ui/components/Image
Explains the correct format for specifying texture paths, including relative paths, omitting extensions, and using forward slashes.
```APIDOC
## Texture Path Format
### Description
Guidelines for formatting texture paths to ensure they are correctly loaded from your Resource Pack.
### Rules
- Paths must be relative to your Resource Pack root.
- File extensions (e.g., `.png`, `.jpg`) should be omitted.
- Use forward slashes (`/`) as path separators.
- The path must exactly match the structure in your Resource Pack.
### Example Resource Pack Structure
```
packs/RP/
└── textures/
└── ui/
├── icons/
│ ├── health.png
│ └── mana.png
└── backgrounds/
└── panel_bg.png
```
### Usage Examples
```jsx
```
```
--------------------------------
### Create a User Authentication Context using createContext
Source: https://bedrock-core.drav.dev/docs/ui/api/createContext
Illustrates the creation of an AuthContext for managing user authentication state. It includes a User interface, the context definition with a null default, and a provider component to manage user login/logout.
```typescript
interface User {
id: string;
name: string;
role: 'admin' | 'user';
}
const AuthContext = createContext(null);
function AuthProvider({ children }: { children: JSX.Element }) {
const [user, setUser] = useState(null);
const login = (newUser: User) => setUser(newUser);
const logout = () => setUser(null);
return (
{children}
);
}
function Dashboard() {
const user = useContext(AuthContext);
if (!user) {
return Not logged in;
}
return (
{`Welcome, ${user.name}!`}{`Role: ${user.role}`}
);
}
```
--------------------------------
### Import Button Component
Source: https://bedrock-core.drav.dev/docs/ui/components/Button
Demonstrates how to import the Button component from the '@bedrock-core/ui' library. This is the first step to using the Button component in your application.
```javascript
import { Button } from '@bedrock-core/ui';
```
--------------------------------
### Toggle Component using useState Hook
Source: https://bedrock-core.drav.dev/docs/ui/hooks/useState
Example of using the useState hook to manage a boolean state for a toggle button. The state changes between 'ON' and 'OFF' when the button is pressed.
```javascript
function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
);
}
```