---
url: /api/ai.md
---
# @sqlrooms/ai
# @sqlrooms/ai
An AI integration package for SQLRooms that provides components and utilities for adding AI-powered features to your data applications. This package enables natural language querying, data analysis, and AI-assisted insights.
## Features
* 🤖 **AI Query Interface**: Natural language to SQL conversion
* 📊 **Automated Analysis**: AI-powered data analysis and insights
* 🔄 **State Management**: Zustand-based state management for AI features
* 🧩 **UI Components**: Ready-to-use components for AI interactions
* 📝 **Query History**: Track and manage AI query history
* 🎯 **Tool Integration**: Framework for AI tools and actions
## Installation
```bash
npm install @sqlrooms/ai
# or
yarn add @sqlrooms/ai
```
Since version 0.8.2, you will need to install the LLM providers you want to use. For example, to use OpenAI, you can install the `@ai-sdk/openai` package:
```bash
npm install @ai-sdk/openai
```
Google LLM provider:
```bash
npm install @ai-sdk/google
```
Anthropic LLM provider:
```bash
npm install @ai-sdk/anthropic
```
DeepSeek LLM provider:
```bash
npm install @ai-sdk/deepseek
```
XAI LLM provider:
```bash
npm install @ai-sdk/xai
```
ollama LLM provider:
```bash
npm install ollama-ai-provider-v2
```
## Basic Usage
### Setting Up AI Integration
```tsx
import {createAiSlice} from '@sqlrooms/ai';
import {createRoomStore} from '@sqlrooms/room-shell';
// Create a room store with AI capabilities
const {roomStore, useRoomStore} = createRoomStore({
// Base room configuration
...createRoomShellSlice({
config: {
// Your room configuration
},
}),
// Add AI slice
...createAiSlice({
getApiKey: (modelProvider) => {
// Return API key for the specified model provider
return process.env.OPENAI_API_KEY || '';
},
initialAnalysisPrompt: 'What insights can you provide from my data?',
// Optional: Add custom tools
customTools: {
// Your custom tools
},
// Optional: Custom instructions for the AI
getInstructions: (tablesSchema) => {
return `Analyze the following tables: ${tablesSchema.map((t) => t.name).join(', ')}`;
},
}),
});
function MyApp() {
return (
);
}
```
### Advanced Store Configuration
For more complex applications, you can combine multiple slices:
```tsx
import {createAiSlice} from '@sqlrooms/ai';
import {
createSqlEditorSlice,
createDefaultSqlEditorConfig,
} from '@sqlrooms/sql-editor';
import {createRoomStore, createRoomShellSlice} from '@sqlrooms/room-shell';
// Define your application state type
export type RoomState = RoomState &
AiSliceState &
SqlEditorSliceState;
// Create the store with multiple slices
export const {roomStore, useRoomStore} = createRoomStore(
(set, get, store) => ({
// Base room slice
...createRoomShellSlice({
config: {
...createDefaultSqlEditorConfig(),
},
}),
// AI slice
...createAiSlice({
config: {
// Optional: Pre-configured AI sessions
sessions: [
{
id: 'default-session',
name: 'Default Analysis',
modelProvider: 'openai',
model: 'gpt-4o',
analysisResults: [],
createdAt: new Date(),
},
],
currentSessionId: 'default-session',
}
getApiKey: (modelProvider) => {
// Return API key based on provider
return apiKeys[modelProvider] || '';
},
// Custom tools and instructions
}),
// SQL Editor slice
...createSqlEditorSlice(),
}),
);
```
### Using AI Query Controls
```tsx
import {QueryControls} from '@sqlrooms/ai';
function AiQueryPanel() {
return (
Ask AI
console.log('Processing query:', query)}
/>
);
}
```
### Displaying Analysis Results
```tsx
import {AnalysisResultsContainer, AnalysisResult} from '@sqlrooms/ai';
function AnalysisPanel() {
// Get the current session and its analysis results
const currentSession = useRoomStore((state) => state.ai.getCurrentSession());
const analysisResults = currentSession?.analysisResults || [];
return (
AI Analysis
{analysisResults.map((result) => (
))}
);
}
```
### Working with AI State
```tsx
function AiStatusIndicator() {
const isRunningAnalysis = useRoomStore((state) => state.ai.isRunningAnalysis);
const analysisPrompt = useRoomStore((state) => state.ai.analysisPrompt);
const currentSession = useRoomStore((state) => state.ai.getCurrentSession());
const lastResult =
currentSession?.analysisResults[currentSession.analysisResults.length - 1];
if (isRunningAnalysis) {
return
AI is analyzing your data...
;
}
if (lastResult?.errorMessage) {
return
Error: {lastResult.errorMessage.message}
;
}
if (analysisPrompt) {
return
Last query: "{analysisPrompt}"
;
}
return
Ask AI a question about your data
;
}
```
## AiSlice API Reference
The AiSlice provides a comprehensive set of state fields and methods for managing AI interactions in your application.
### State Fields
#### `analysisPrompt`
The current prompt text entered by the user for analysis.
```tsx
const prompt = useRoomStore((state) => state.ai.analysisPrompt);
```
#### `isRunningAnalysis`
Boolean flag indicating whether an analysis is currently in progress.
```tsx
const isRunning = useRoomStore((state) => state.ai.isRunningAnalysis);
```
#### `tools`
Record of available AI tools that can be used during analysis.
```tsx
const availableTools = useRoomStore((state) => state.ai.tools);
```
#### `analysisAbortController`
Optional AbortController instance that can be used to cancel an ongoing analysis.
```tsx
const abortController = useRoomStore(
(state) => state.ai.analysisAbortController,
);
```
### Methods
#### `setAnalysisPrompt(prompt: string)`
Sets the current analysis prompt text.
```tsx
const setPrompt = useRoomStore((state) => state.ai.setAnalysisPrompt);
setPrompt('Analyze sales trends for the last quarter');
```
#### `startAnalysis()`
Starts the analysis process using the current prompt.
```tsx
const startAnalysis = useRoomStore((state) => state.ai.startAnalysis);
await startAnalysis();
```
#### `cancelAnalysis()`
Cancels any ongoing analysis.
```tsx
const cancelAnalysis = useRoomStore((state) => state.ai.cancelAnalysis);
cancelAnalysis();
```
#### `setAiModel(modelProvider: string, model: string)`
Sets the AI model and provider for the current session.
```tsx
const setModel = useRoomStore((state) => state.ai.setAiModel);
setModel('openai', 'gpt-4o');
```
#### `createSession(name?: string, modelProvider?: string, model?: string)`
Creates a new analysis session with optional name and model settings.
```tsx
const createSession = useRoomStore((state) => state.ai.createSession);
createSession('Financial Analysis', 'openai', 'gpt-4o');
```
#### `switchSession(sessionId: string)`
Switches to a different analysis session by ID.
```tsx
const switchSession = useRoomStore((state) => state.ai.switchSession);
switchSession('session-123');
```
#### `renameSession(sessionId: string, name: string)`
Renames an existing analysis session.
```tsx
const renameSession = useRoomStore((state) => state.ai.renameSession);
renameSession('session-123', 'Q4 Sales Analysis');
```
#### `deleteSession(sessionId: string)`
Deletes an analysis session by ID.
```tsx
const deleteSession = useRoomStore((state) => state.ai.deleteSession);
deleteSession('session-123');
```
#### `getCurrentSession()`
Returns the current active analysis session.
```tsx
const currentSession = useRoomStore((state) => state.ai.getCurrentSession());
```
#### `deleteAnalysisResult(sessionId: string, resultId: string)`
Deletes a specific analysis result from a session.
```tsx
const deleteResult = useRoomStore((state) => state.ai.deleteAnalysisResult);
deleteResult('session-123', 'result-456');
```
#### `findToolComponent(toolName: string)`
Finds the React component associated with a specific tool.
```tsx
const ChartComponent = useRoomStore((state) =>
state.ai.findToolComponent('chart'),
);
```
## Data Structure
The basic data structure of the AI package is:
```ts
ai: {
sessions: [
{
id: defaultSessionId,
name: 'Default Session',
modelProvider: 'openai',
model: 'gpt-4o-mini',
analysisResults: [],
createdAt: new Date(),
},
],
currentSessionId: defaultSessionId,
}
```
Each session has a `analysisResults` which is an array of `AnalysisResult`. Each `AnalysisResult` has the following properties:
* `id`: The unique identifier for the analysis result
* `prompt`: The user prompt that was used to generate the analysis result
* `streamMessage`: The stream message from the LLM
* `errorMessage`: The error message from the LLM
* `isCompleted`: Whether the analysis result has been completed
For each user prompt, the LLM will run multiple tools (e.g. `query`, `chart`) and return the result as the `streamMessage`. The structure of the `streamMessage` is as follows:
* `text`: the final response from the LLM (streamable)
* `reasoning`: the reasoning of the LLM (only for reason models)
* `toolCallMessages`: the message array of the tool calls executed by the LLM
Each `toolCallMessages` has the following properties:
* `toolName`: the name of the tool
* `toolCallId`: the id of the tool call
* `args`: the arguments of the tool call
* `llmResult`: the result from the execution of the tool, which will be sent back to the LLM as response.
* `additionalData`: the additional data of the tool, which can be used to pass the output of the tool to next tool call or the component for rendering.
## Rendering
```text
|--------------------------------|
| AnalysisResultsContainer |
|--------------------------------|
| |--------------------------| |
| | AnalysisResult | |
| | | |
| | streamMessage | |
| | | |
| | |---------------------| | |
| | | Tools | | |
| | |---------------------| | |
| | | |---------------| | | |
| | | |ToolCallMessage| | | |
| | | |---------------| | | |
| | | |---------------| | | |
| | | |ToolCallMessage| | | |
| | | |---------------| | | |
| | | ... | | |
| | |---------------------| | |
| | | |
| | text | |
| |--------------------------| |
|--------------------------------|
```
## Tools
In AI package, we provide a tool() to allow creating function tool for LLM to use. It is an extension of the `tool` from `vercel ai sdk`, and it supports not only `execute` function, but also `context` object and `component` object:
* `execute` needs to return
* llmResult: the result send back to LLM (no raw data)
* additionalData: the data will be used by `component` and next `tool`
* `context`
* provide e.g. runtime or async data for `execute`
* `execute` can access `context` via `options.context`
* `component`
* use `additionalData` to render a React component for this `tool`
For example, the `query` tool is defined as follows:
```ts
const functions = {
weather: tool({
description: 'Get the weather in a city from a weather station',
parameters: z.object({cityName: z.string()}),
execute: async ({cityName}, options) => {
const getStation = options.context?.getStation;
const station = getStation ? await getStation(cityName) : null;
return {
llmResult: `The weather in ${cityName} is sunny from weather station ${station}.`,
additionalData: {
weather: 'sunny',
station,
},
};
},
context: {
getStation: async (cityName: string) => {
const stations = {
'New York': '123',
'Los Angeles': '456',
Chicago: '789',
};
return stations[cityName];
},
},
component: WeatherStation,
}),
};
```
## Advanced Features
* **Custom AI Tools**: Define custom tools for AI to use with the tool() function
* **Multiple Sessions**: Create and manage multiple analysis sessions for different purposes
* **Model Selection**: Switch between different AI models and providers
* **Result Management**: Save, delete, and organize analysis results
* **Conversation Context**: Maintain context across multiple queries in a session
* **Feedback Loop**: Collect user feedback to improve AI responses
For more information, visit the SQLRooms documentation.
## AI Settings Configuration
This package now includes comprehensive AI settings components. These components provide a complete set of UI elements for managing AI model configuration, parameters, and usage tracking.
### AI Settings Features
* **createAiSettingsSlice**: Function to create a Zustand slice for managing AI model configuration with room-shell integration
* **AiSettingsPanel**: Main configuration panel with modular sub-components for different configuration aspects
* **ProvidersSettings**: Component for configuring AI providers (OpenAI, Anthropic, etc.) with API keys and base URLs
* **ModelsSettings**: Component for managing available models and their parameters
* **ModelParametersSettings**: Component for configuring model parameters like max steps and system instructions
* **ModelSelector**: Standalone model selector component for quick model switching
### AI Settings Usage
#### Individual Components
```tsx
import {
AiSettingsPanel,
ModelSelector,
} from '@sqlrooms/ai';
import {useRoomStore} from '../store';
// Main configuration panel with sub-components
// Standalone model selector
```
### AI Settings API Reference
#### Core Components
* **`AiSettingsPanel`**: Main configuration panel with modular sub-components
* `AiSettingsPanel.ProvidersSettings`: Configure AI providers (OpenAI, Anthropic, etc.)
* `AiSettingsPanel.ModelsSettings`: Manage available models and their parameters
* `AiSettingsPanel.ModelParametersSettings`: Configure model parameters and instructions
* **`ModelSelector`**: Standalone model selector for quick switching
#### Slice Configuration
The package uses a slice-based configuration system that integrates with SQLRooms room-shell:
* **`createAiSettingsSlice()`**: Creates the AI settings configuration slice for state management
* **`AiSettingsSliceConfig`**: TypeScript type for configuration schema
* **`createDefaultAiSettings(providers)`**: Helper to create default configuration with providers
* **`getApiKey(config, provider, model)`**: Utility to get API key from configuration
* **`getBaseUrl(config, provider, model)`**: Utility to get base URL from configuration
#### Store Integration
The AI settings configuration integrates with the main AI slice through helper functions:
* **`getApiKey()`**: Function to retrieve API key from current session and model config
* **`getMaxSteps()`**: Function to get max steps from model configuration
* **`getBaseUrl()`**: Function to get base URL from current session and model config
* **`getInstructions(tablesSchema)`**: Function to generate system instructions with optional custom instructions
## Interfaces
* [ModelUsageData](interfaces/ModelUsageData.md)
## Type Aliases
* [AiSettingsSliceConfig](type-aliases/AiSettingsSliceConfig.md)
* [AiSliceConfig](type-aliases/AiSliceConfig.md)
* [ErrorMessageSchema](type-aliases/ErrorMessageSchema.md)
* [AnalysisResultSchema](type-aliases/AnalysisResultSchema.md)
* [AnalysisSessionSchema](type-aliases/AnalysisSessionSchema.md)
* [AiSliceTool](type-aliases/AiSliceTool.md)
* [AiSliceState](type-aliases/AiSliceState.md)
* [SessionType](type-aliases/SessionType.md)
* [AiSettingsSliceState](type-aliases/AiSettingsSliceState.md)
* [DefaultToolsOptions](type-aliases/DefaultToolsOptions.md)
* [QueryToolParameters](type-aliases/QueryToolParameters.md)
## Variables
* [AiSettingsSliceConfig](variables/AiSettingsSliceConfig.md)
* [AiSliceConfig](variables/AiSliceConfig.md)
* [ErrorMessageSchema](variables/ErrorMessageSchema.md)
* [AnalysisResultSchema](variables/AnalysisResultSchema.md)
* [AnalysisSessionSchema](variables/AnalysisSessionSchema.md)
* [QueryToolParameters](variables/QueryToolParameters.md)
## Functions
* [createDefaultAiConfig](functions/createDefaultAiConfig.md)
* [createAiSlice](functions/createAiSlice.md)
* [useStoreWithAi](functions/useStoreWithAi.md)
* [AnalysisResult](functions/AnalysisResult.md)
* [AnalysisResultsContainer](functions/AnalysisResultsContainer.md)
* [ModelSelector](functions/ModelSelector.md)
* [QueryControls](functions/QueryControls.md)
* [SessionControls](functions/SessionControls.md)
* [DeleteSessionDialog](functions/DeleteSessionDialog.md)
* [SessionActions](functions/SessionActions.md)
* [SessionDropdown](functions/SessionDropdown.md)
* [SessionTitle](functions/SessionTitle.md)
* [ToolErrorMessage](functions/ToolErrorMessage.md)
* [useScrollToBottom](functions/useScrollToBottom.md)
* [createAiSettingsSlice](functions/createAiSettingsSlice.md)
* [useStoreWithAiSettings](functions/useStoreWithAiSettings.md)
* [AiModelParameters](functions/AiModelParameters.md)
* [AiModelUsage](functions/AiModelUsage.md)
* [AiModelsSettings](functions/AiModelsSettings.md)
* [AiProvidersSettings](functions/AiProvidersSettings.md)
* [AiSettingsPanel](functions/AiSettingsPanel.md)
* [createDefaultAiSettingsConfig](functions/createDefaultAiSettingsConfig.md)
* [createDefaultAiInstructions](functions/createDefaultAiInstructions.md)
* [createDefaultAiTools](functions/createDefaultAiTools.md)
* [QueryToolResult](functions/QueryToolResult.md)
---
---
url: /api/ai-config.md
---
# @sqlrooms/ai-config
## Type Aliases
* [AiSettingsSliceConfig](type-aliases/AiSettingsSliceConfig.md)
* [AiSliceConfig](type-aliases/AiSliceConfig.md)
* [ErrorMessageSchema](type-aliases/ErrorMessageSchema.md)
* [AnalysisResultSchema](type-aliases/AnalysisResultSchema.md)
* [AnalysisSessionSchema](type-aliases/AnalysisSessionSchema.md)
## Variables
* [AiSettingsSliceConfig](variables/AiSettingsSliceConfig.md)
* [AiSliceConfig](variables/AiSliceConfig.md)
* [ErrorMessageSchema](variables/ErrorMessageSchema.md)
* [AnalysisResultSchema](variables/AnalysisResultSchema.md)
* [AnalysisSessionSchema](variables/AnalysisSessionSchema.md)
## Functions
* [createDefaultAiConfig](functions/createDefaultAiConfig.md)
---
---
url: /api/ai-core.md
---
# @sqlrooms/ai-core
# @sqlrooms/ai
An AI integration package for SQLRooms that provides components and utilities for adding AI-powered features to your data applications. This package enables natural language querying, data analysis, and AI-assisted insights.
## Features
* 🤖 **AI Query Interface**: Natural language to SQL conversion
* 📊 **Automated Analysis**: AI-powered data analysis and insights
* 🔄 **State Management**: Zustand-based state management for AI features
* 🧩 **UI Components**: Ready-to-use components for AI interactions
* 📝 **Query History**: Track and manage AI query history
* 🎯 **Tool Integration**: Framework for AI tools and actions
## Installation
```bash
npm install @sqlrooms/ai
# or
yarn add @sqlrooms/ai
```
Since version 0.8.2, you will need to install the LLM providers you want to use. For example, to use OpenAI, you can install the `@ai-sdk/openai` package:
```bash
npm install @ai-sdk/openai
```
Google LLM provider:
```bash
npm install @ai-sdk/google
```
Anthropic LLM provider:
```bash
npm install @ai-sdk/anthropic
```
DeepSeek LLM provider:
```bash
npm install @ai-sdk/deepseek
```
XAI LLM provider:
```bash
npm install @ai-sdk/xai
```
ollama LLM provider:
```bash
npm install ollama-ai-provider-v2
```
## Basic Usage
### Setting Up AI Integration
```tsx
import {createAiSlice} from '@sqlrooms/ai';
import {createRoomStore} from '@sqlrooms/room-shell';
// Create a room store with AI capabilities
const {roomStore, useRoomStore} = createRoomStore({
// Base room configuration
...createRoomShellSlice({
config: {
// Your room configuration
},
}),
// Add AI slice
...createAiSlice({
getApiKey: (modelProvider) => {
// Return API key for the specified model provider
return process.env.OPENAI_API_KEY || '';
},
initialAnalysisPrompt: 'What insights can you provide from my data?',
// Optional: Add custom tools
customTools: {
// Your custom tools
},
// Optional: Custom instructions for the AI
getInstructions: (tablesSchema) => {
return `Analyze the following tables: ${tablesSchema.map((t) => t.name).join(', ')}`;
},
}),
});
function MyApp() {
return (
);
}
```
### Advanced Store Configuration
For more complex applications, you can combine multiple slices:
```tsx
import {createAiSlice} from '@sqlrooms/ai';
import {
createSqlEditorSlice,
createDefaultSqlEditorConfig,
} from '@sqlrooms/sql-editor';
import {createRoomStore, createRoomShellSlice} from '@sqlrooms/room-shell';
// Define your application state type
export type RoomState = RoomState &
AiSliceState &
SqlEditorSliceState;
// Create the store with multiple slices
export const {roomStore, useRoomStore} = createRoomStore(
(set, get, store) => ({
// Base room slice
...createRoomShellSlice({
config: {
...createDefaultSqlEditorConfig(),
},
}),
// AI slice
...createAiSlice({
config: {
// Optional: Pre-configured AI sessions
sessions: [
{
id: 'default-session',
name: 'Default Analysis',
modelProvider: 'openai',
model: 'gpt-4o',
analysisResults: [],
createdAt: new Date(),
},
],
currentSessionId: 'default-session',
}
getApiKey: (modelProvider) => {
// Return API key based on provider
return apiKeys[modelProvider] || '';
},
// Custom tools and instructions
}),
// SQL Editor slice
...createSqlEditorSlice(),
}),
);
```
### Using AI Query Controls
```tsx
import {QueryControls} from '@sqlrooms/ai';
function AiQueryPanel() {
return (
Ask AI
console.log('Processing query:', query)}
/>
);
}
```
### Displaying Analysis Results
```tsx
import {AnalysisResultsContainer, AnalysisResult} from '@sqlrooms/ai';
function AnalysisPanel() {
// Get the current session and its analysis results
const currentSession = useRoomStore((state) => state.ai.getCurrentSession());
const analysisResults = currentSession?.analysisResults || [];
return (
AI Analysis
{analysisResults.map((result) => (
))}
);
}
```
### Working with AI State
```tsx
function AiStatusIndicator() {
const isRunningAnalysis = useRoomStore((state) => state.ai.isRunningAnalysis);
const analysisPrompt = useRoomStore((state) => state.ai.analysisPrompt);
const currentSession = useRoomStore((state) => state.ai.getCurrentSession());
const lastResult =
currentSession?.analysisResults[currentSession.analysisResults.length - 1];
if (isRunningAnalysis) {
return
AI is analyzing your data...
;
}
if (lastResult?.errorMessage) {
return
Error: {lastResult.errorMessage.message}
;
}
if (analysisPrompt) {
return
Last query: "{analysisPrompt}"
;
}
return
Ask AI a question about your data
;
}
```
## AiSlice API Reference
The AiSlice provides a comprehensive set of state fields and methods for managing AI interactions in your application.
### State Fields
#### `analysisPrompt`
The current prompt text entered by the user for analysis.
```tsx
const prompt = useRoomStore((state) => state.ai.analysisPrompt);
```
#### `isRunningAnalysis`
Boolean flag indicating whether an analysis is currently in progress.
```tsx
const isRunning = useRoomStore((state) => state.ai.isRunningAnalysis);
```
#### `tools`
Record of available AI tools that can be used during analysis.
```tsx
const availableTools = useRoomStore((state) => state.ai.tools);
```
#### `analysisAbortController`
Optional AbortController instance that can be used to cancel an ongoing analysis.
```tsx
const abortController = useRoomStore(
(state) => state.ai.analysisAbortController,
);
```
### Methods
#### `setAnalysisPrompt(prompt: string)`
Sets the current analysis prompt text.
```tsx
const setPrompt = useRoomStore((state) => state.ai.setAnalysisPrompt);
setPrompt('Analyze sales trends for the last quarter');
```
#### `startAnalysis()`
Starts the analysis process using the current prompt.
```tsx
const startAnalysis = useRoomStore((state) => state.ai.startAnalysis);
await startAnalysis();
```
#### `cancelAnalysis()`
Cancels any ongoing analysis.
```tsx
const cancelAnalysis = useRoomStore((state) => state.ai.cancelAnalysis);
cancelAnalysis();
```
#### `setAiModel(modelProvider: string, model: string)`
Sets the AI model and provider for the current session.
```tsx
const setModel = useRoomStore((state) => state.ai.setAiModel);
setModel('openai', 'gpt-4o');
```
#### `createSession(name?: string, modelProvider?: string, model?: string)`
Creates a new analysis session with optional name and model settings.
```tsx
const createSession = useRoomStore((state) => state.ai.createSession);
createSession('Financial Analysis', 'openai', 'gpt-4o');
```
#### `switchSession(sessionId: string)`
Switches to a different analysis session by ID.
```tsx
const switchSession = useRoomStore((state) => state.ai.switchSession);
switchSession('session-123');
```
#### `renameSession(sessionId: string, name: string)`
Renames an existing analysis session.
```tsx
const renameSession = useRoomStore((state) => state.ai.renameSession);
renameSession('session-123', 'Q4 Sales Analysis');
```
#### `deleteSession(sessionId: string)`
Deletes an analysis session by ID.
```tsx
const deleteSession = useRoomStore((state) => state.ai.deleteSession);
deleteSession('session-123');
```
#### `getCurrentSession()`
Returns the current active analysis session.
```tsx
const currentSession = useRoomStore((state) => state.ai.getCurrentSession());
```
#### `deleteAnalysisResult(sessionId: string, resultId: string)`
Deletes a specific analysis result from a session.
```tsx
const deleteResult = useRoomStore((state) => state.ai.deleteAnalysisResult);
deleteResult('session-123', 'result-456');
```
#### `findToolComponent(toolName: string)`
Finds the React component associated with a specific tool.
```tsx
const ChartComponent = useRoomStore((state) =>
state.ai.findToolComponent('chart'),
);
```
## Data Structure
The basic data structure of the AI package is:
```ts
ai: {
sessions: [
{
id: defaultSessionId,
name: 'Default Session',
modelProvider: 'openai',
model: 'gpt-4o-mini',
analysisResults: [],
createdAt: new Date(),
},
],
currentSessionId: defaultSessionId,
}
```
Each session has a `analysisResults` which is an array of `AnalysisResult`. Each `AnalysisResult` has the following properties:
* `id`: The unique identifier for the analysis result
* `prompt`: The user prompt that was used to generate the analysis result
* `streamMessage`: The stream message from the LLM
* `errorMessage`: The error message from the LLM
* `isCompleted`: Whether the analysis result has been completed
For each user prompt, the LLM will run multiple tools (e.g. `query`, `chart`) and return the result as the `streamMessage`. The structure of the `streamMessage` is as follows:
* `text`: the final response from the LLM (streamable)
* `reasoning`: the reasoning of the LLM (only for reason models)
* `toolCallMessages`: the message array of the tool calls executed by the LLM
Each `toolCallMessages` has the following properties:
* `toolName`: the name of the tool
* `toolCallId`: the id of the tool call
* `args`: the arguments of the tool call
* `llmResult`: the result from the execution of the tool, which will be sent back to the LLM as response.
* `additionalData`: the additional data of the tool, which can be used to pass the output of the tool to next tool call or the component for rendering.
## Rendering
```text
|--------------------------------|
| AnalysisResultsContainer |
|--------------------------------|
| |--------------------------| |
| | AnalysisResult | |
| | | |
| | streamMessage | |
| | | |
| | |---------------------| | |
| | | Tools | | |
| | |---------------------| | |
| | | |---------------| | | |
| | | |ToolCallMessage| | | |
| | | |---------------| | | |
| | | |---------------| | | |
| | | |ToolCallMessage| | | |
| | | |---------------| | | |
| | | ... | | |
| | |---------------------| | |
| | | |
| | text | |
| |--------------------------| |
|--------------------------------|
```
## Tools
In AI package, we provide a tool() to allow creating function tool for LLM to use. It is an extension of the `tool` from `vercel ai sdk`, and it supports not only `execute` function, but also `context` object and `component` object:
* `execute` needs to return
* llmResult: the result send back to LLM (no raw data)
* additionalData: the data will be used by `component` and next `tool`
* `context`
* provide e.g. runtime or async data for `execute`
* `execute` can access `context` via `options.context`
* `component`
* use `additionalData` to render a React component for this `tool`
For example, the `query` tool is defined as follows:
```ts
const functions = {
weather: tool({
description: 'Get the weather in a city from a weather station',
parameters: z.object({cityName: z.string()}),
execute: async ({cityName}, options) => {
const getStation = options.context?.getStation;
const station = getStation ? await getStation(cityName) : null;
return {
llmResult: `The weather in ${cityName} is sunny from weather station ${station}.`,
additionalData: {
weather: 'sunny',
station,
},
};
},
context: {
getStation: async (cityName: string) => {
const stations = {
'New York': '123',
'Los Angeles': '456',
Chicago: '789',
};
return stations[cityName];
},
},
component: WeatherStation,
}),
};
```
## Advanced Features
* **Custom AI Tools**: Define custom tools for AI to use with the tool() function
* **Multiple Sessions**: Create and manage multiple analysis sessions for different purposes
* **Model Selection**: Switch between different AI models and providers
* **Result Management**: Save, delete, and organize analysis results
* **Conversation Context**: Maintain context across multiple queries in a session
* **Feedback Loop**: Collect user feedback to improve AI responses
For more information, visit the SQLRooms documentation.
## Type Aliases
* [AiSliceConfig](type-aliases/AiSliceConfig.md)
* [AiSliceTool](type-aliases/AiSliceTool.md)
* [AiSliceState](type-aliases/AiSliceState.md)
* [SessionType](type-aliases/SessionType.md)
## Variables
* [AiSliceConfig](variables/AiSliceConfig.md)
## Functions
* [createDefaultAiConfig](functions/createDefaultAiConfig.md)
* [createAiSlice](functions/createAiSlice.md)
* [useStoreWithAi](functions/useStoreWithAi.md)
* [AnalysisResult](functions/AnalysisResult.md)
* [AnalysisResultsContainer](functions/AnalysisResultsContainer.md)
* [ModelSelector](functions/ModelSelector.md)
* [QueryControls](functions/QueryControls.md)
* [SessionControls](functions/SessionControls.md)
* [DeleteSessionDialog](functions/DeleteSessionDialog.md)
* [SessionActions](functions/SessionActions.md)
* [SessionDropdown](functions/SessionDropdown.md)
* [SessionTitle](functions/SessionTitle.md)
* [ToolErrorMessage](functions/ToolErrorMessage.md)
* [useScrollToBottom](functions/useScrollToBottom.md)
---
---
url: /api/ai-settings.md
---
# @sqlrooms/ai-settings
# @sqlrooms/ai
AI settings UI and state management
## Interfaces
* [ModelUsageData](interfaces/ModelUsageData.md)
## Type Aliases
* [AiSettingsSliceConfig](type-aliases/AiSettingsSliceConfig.md)
* [AiSettingsSliceState](type-aliases/AiSettingsSliceState.md)
## Variables
* [AiSettingsSliceConfig](variables/AiSettingsSliceConfig.md)
## Functions
* [createAiSettingsSlice](functions/createAiSettingsSlice.md)
* [useStoreWithAiSettings](functions/useStoreWithAiSettings.md)
* [AiModelParameters](functions/AiModelParameters.md)
* [AiModelUsage](functions/AiModelUsage.md)
* [AiModelsSettings](functions/AiModelsSettings.md)
* [AiProvidersSettings](functions/AiProvidersSettings.md)
* [AiSettingsPanel](functions/AiSettingsPanel.md)
* [createDefaultAiSettingsConfig](functions/createDefaultAiSettingsConfig.md)
---
---
url: /api/canvas.md
---
# @sqlrooms/canvas
# @sqlrooms/canvas
ReactFlow-based canvas for building and editing DAGs of SQL and Vega nodes, with a Zustand slice for persistence in SQLRooms apps.
* CanvasSlice stores nodes and edges under `canvas.config`
* Canvas component renders and edits the graph
## Type Aliases
* [CanvasSliceConfig](type-aliases/CanvasSliceConfig.md)
* [CanvasSliceState](type-aliases/CanvasSliceState.md)
## Variables
* [CanvasSliceConfig](variables/CanvasSliceConfig.md)
## Functions
* [Canvas](functions/Canvas.md)
* [createDefaultCanvasConfig](functions/createDefaultCanvasConfig.md)
* [createCanvasSlice](functions/createCanvasSlice.md)
---
---
url: /api/cosmos.md
---
# @sqlrooms/cosmos
A powerful graph visualization package for SQLRooms applications. This package provides React components and hooks for creating interactive graph visualizations using a WebGL-based graph rendering engine, with state management through Zustand.
This package is built on top of the [Cosmos library](https://github.com/cosmograph-org/cosmos), a GPU-accelerated force graph layout and rendering library.
## Features
* 🌐 **Interactive Graphs**: Create dynamic, interactive graph visualizations
* 🚀 **WebGL Rendering**: High-performance rendering for large graphs
* 🧩 **React Components**: Ready-to-use components for graph visualization
* 🔄 **State Management**: Zustand-based state management for graph state
* 🎛️ **Simulation Controls**: Fine-grained control over physics simulation
* 🎨 **Customizable Styling**: Extensive options for visual customization
## Installation
```bash
npm install @sqlrooms/cosmos
```
## Basic Usage
### Simple Graph Visualization
```tsx
import {
CosmosGraph,
CosmosGraphControls,
createDefaultCosmosConfig,
} from '@sqlrooms/cosmos';
function MyGraph() {
const graphData = {
nodes: [
{id: 'node1', label: 'Node 1'},
{id: 'node2', label: 'Node 2'},
{id: 'node3', label: 'Node 3'},
],
links: [
{source: 'node1', target: 'node2'},
{source: 'node2', target: 'node3'},
{source: 'node3', target: 'node1'},
],
};
return (
);
}
```
### With Simulation Controls
```tsx
import {
CosmosGraph,
CosmosGraphControls,
CosmosSimulationControls,
createDefaultCosmosConfig,
} from '@sqlrooms/cosmos';
function AdvancedGraph() {
return (
);
}
```
### Using with Zustand Store
```tsx
import {
createCosmosSlice,
useStoreWithCosmos,
createDefaultCosmosConfig,
} from '@sqlrooms/cosmos';
import {createRoomStore} from '@sqlrooms/room-shell';
// Create a room store with cosmos capabilities
const useStore = createRoomStore({
cosmos: createCosmosSlice(createDefaultCosmosConfig()),
});
function GraphWithState() {
const {setGraphData, toggleSimulation, isSimulationRunning, zoomToFit} =
useStoreWithCosmos(useStore);
// Load graph data
useEffect(() => {
setGraphData(myGraphData);
}, []);
return (
);
}
```
## Configuration
The Cosmos graph visualization system provides extensive configuration options for both visual appearance and physics simulation.
### Visual Configuration
```tsx
const config = {
pointSizeScale: 1.2, // Base scale for node sizes
scalePointsOnZoom: true, // Dynamic node sizing with zoom
renderLinks: true, // Toggle link visibility
linkArrows: true, // Show directional arrows
curvedLinks: true, // Use curved links
linkWidth: 1.5, // Width of links
linkOpacity: 0.8, // Opacity of links
// ... other visual options
};
```
### Physics Simulation Configuration
```tsx
const config = {
simulationGravity: 0.2, // Center attraction strength
simulationRepulsion: 1.0, // Node repulsion strength
simulationLinkSpring: 1.2, // Link elasticity
simulationLinkDistance: 15, // Preferred link distance
simulationFriction: 0.85, // Movement damping
simulationDecay: 1000, // Simulation cooling rate
// ... other physics options
};
```
## Advanced Features
* **Custom Node Rendering**: Define custom renderers for nodes
* **Interactive Events**: Handle click, hover, and drag events
* **Data Binding**: Connect graph data to your application state
* **Layout Algorithms**: Apply different layout algorithms
* **Performance Optimization**: Options for handling large graphs
For more information, visit the SQLRooms documentation.
## About Cosmograph Cosmos
This package is built on top of [Cosmograph Cosmos](https://github.com/cosmograph-org/cosmos), a GPU-accelerated force graph layout and rendering library. Cosmograph Cosmos offers:
* **GPU Acceleration**: All computations and rendering happen on the GPU in fragment and vertex shaders
* **High Performance**: Capable of rendering hundreds of thousands of nodes and links in real-time
* **WebGL-based**: Utilizes WebGL for efficient graph visualization
* **Advanced Physics**: Sophisticated force-directed layout algorithms
For more information about the underlying library, visit the [Cosmograph Cosmos GitHub repository](https://github.com/cosmograph-org/cosmos) or the [official documentation](https://cosmograph-org.github.io/cosmos/).
## Type Aliases
* [CosmosGraphProps](type-aliases/CosmosGraphProps.md)
* [CosmosSliceState](type-aliases/CosmosSliceState.md)
* [RoomStateWithCosmos](type-aliases/RoomStateWithCosmos.md)
* [CosmosSliceConfig](type-aliases/CosmosSliceConfig.md)
## Variables
* [CosmosSliceConfig](variables/CosmosSliceConfig.md)
## Functions
* [CosmosGraph](functions/CosmosGraph.md)
* [CosmosGraphControls](functions/CosmosGraphControls.md)
* [CosmosSimulationControls](functions/CosmosSimulationControls.md)
* [createCosmosSlice](functions/createCosmosSlice.md)
* [useStoreWithCosmos](functions/useStoreWithCosmos.md)
* [createDefaultCosmosConfig](functions/createDefaultCosmosConfig.md)
* [useHoverState](functions/useHoverState.md)
## References
### CosmosSliceConfigType
Renames and re-exports [CosmosSliceConfig](variables/CosmosSliceConfig.md)
---
---
url: /api/data-table.md
---
# @sqlrooms/data-table
A high-performance data table component library for SQLRooms applications. This package provides flexible and feature-rich table components for displaying and interacting with large datasets, with special support for Apache Arrow data structures.
## Features
* 📊 **Multiple Table Variants**: Paginated, virtualized, and query-specific tables
* 🚀 **High Performance**: Optimized for handling large datasets efficiently
* 🏹 **Arrow Integration**: Native support for Apache Arrow data structures
* 🔍 **Sorting & Filtering**: Built-in data manipulation capabilities
* 📱 **Responsive Design**: Tables that work well on all screen sizes
* 🎨 **Customizable**: Flexible styling and configuration options
## Installation
```bash
npm install @sqlrooms/data-table
# or
yarn add @sqlrooms/data-table
```
## Basic Usage
### Paginated Data Table
```tsx
import {DataTablePaginated} from '@sqlrooms/data-table';
function MyDataTable() {
const data = [
{id: 1, name: 'Alice', age: 28},
{id: 2, name: 'Bob', age: 34},
{id: 3, name: 'Charlie', age: 42},
// More data...
];
const columns = [
{accessorKey: 'id', header: 'ID'},
{accessorKey: 'name', header: 'Name'},
{accessorKey: 'age', header: 'Age'},
];
return (
);
}
```
### Working with SQL Query Results
```tsx
import {QueryDataTable} from '@sqlrooms/data-table';
import {useSql} from '@sqlrooms/duckdb';
function QueryResultsTable() {
const {data, isLoading, error} = useSql({
query:
'SELECT id, name, email, created_at FROM users ORDER BY created_at DESC',
});
if (isLoading) return
Loading...
;
if (error) return
Error: {error.message}
;
if (!data) return null;
return ;
}
```
### Using with Apache Arrow
```tsx
import {useArrowDataTable} from '@sqlrooms/data-table';
import {Table} from 'apache-arrow';
function ArrowTable({arrowTable}: {arrowTable: Table}) {
const {columns, data} = useArrowDataTable(arrowTable);
return ;
}
```
## Advanced Features
* **Custom Cell Rendering**: Define custom renderers for specific cell types
* **Row Selection**: Enable row selection with checkboxes
* **Expandable Rows**: Show additional details in expandable row sections
* **Column Resizing**: Allow users to resize columns
* **Export Options**: Export table data to CSV or other formats
* **Theming**: Customize the appearance to match your application
For more information, visit the SQLRooms documentation.
## Type Aliases
* [DataTablePaginatedProps](type-aliases/DataTablePaginatedProps.md)
## Functions
* [ColumnTypeBadge](functions/ColumnTypeBadge.md)
* [DataTableArrowPaginated](functions/DataTableArrowPaginated.md)
* [DataTableModal](functions/DataTableModal.md)
* [DataTablePaginated](functions/DataTablePaginated.md)
* [~~DataTableVirtualized~~](functions/DataTableVirtualized.md)
* [QueryDataTable](functions/QueryDataTable.md)
* [QueryDataTableActionsMenu](functions/QueryDataTableActionsMenu.md)
* [useArrowDataTable](functions/useArrowDataTable.md)
* [makePagedQuery](functions/makePagedQuery.md)
---
---
url: /api/discuss.md
---
# @sqlrooms/discuss
A simple discussion system for SQLRooms applications. Can be used for commenting and annotation with support for threaded conversations, real-time updates, and anchor-based discussions.
## Overview
The `@sqlrooms/discuss` module provides a complete discussion system with the following key features:
* **Threaded conversations**: Support for replies to discussions and comments
* **Anchor-based discussions**: Link discussions to specific data points or UI elements
* **Real-time state management**: Built on Zustand for reactive updates
* **Customizable rendering**: Flexible component system for custom UI implementations
* **Delete confirmation**: Built-in confirmation dialogs for safe content removal
* **Highlighting**: Visual highlighting of specific discussions
## Main Components
### Core Components
#### `DiscussionList`
The main container component that renders all discussions with built-in forms for adding, editing, and replying to content.
```tsx
import {DiscussionList} from '@sqlrooms/discuss';
}
renderDiscussion={(props) => }
/>;
```
#### `CommentItem`
Individual comment renderer with built-in edit/delete actions.
```tsx
import {CommentItem} from '@sqlrooms/discuss';
;
```
#### `DiscussionItem`
Container for a complete discussion thread including root comment and replies.
```tsx
import {DiscussionItem} from '@sqlrooms/discuss';
;
```
### Store Integration
#### Store Setup with `createDiscussSlice`
To use the discussion system, you need to integrate it with your room store using `createDiscussSlice`:
```tsx
import {
createDefaultDiscussConfig,
createDiscussSlice,
DiscussSliceConfig,
DiscussSliceState,
} from '@sqlrooms/discuss';
import {
BaseRoomConfig,
createRoomShellSlice,
createRoomStore,
RoomShellSliceState,
} from '@sqlrooms/room-shell';
import {z} from 'zod';
// 1. Extend your app config with DiscussSliceConfig
export const RoomConfig = BaseRoomConfig.merge(DiscussSliceConfig);
export type RoomConfig = z.infer;
// 2. Extend your app state with DiscussSliceState
export type RoomState = RoomShellSliceState & DiscussSliceState;
// 3. Create the store with discuss slice
export const {roomStore, useRoomStore} = createRoomStore(
(set, get, store) => ({
// Add the discuss slice with a user ID
...createDiscussSlice({userId: 'current-user-id'})(set, get, store),
// Add your room shell slice
...createRoomShellSlice({
connector: yourDatabaseConnector,
config: {
// Include default discuss config
...createDefaultDiscussConfig(),
// Your other config...
layout: {
/* your layout */
},
dataSources: [
/* your data sources */
],
},
room: {
// Your room configuration
},
})(set, get, store),
}),
);
```
#### Using the Store Hook
Access discussion state and actions using the provided hook:
```tsx
import {useStoreWithDiscussion} from '@sqlrooms/discuss';
function MyComponent() {
// Get discussions
const discussions = useStoreWithDiscussion(
(state) => state.discuss.config.discussions,
);
// Get actions
const addDiscussion = useStoreWithDiscussion(
(state) => state.discuss.addDiscussion,
);
const setReplyToItem = useStoreWithDiscussion(
(state) => state.discuss.setReplyToItem,
);
// Add a new discussion
const handleAddDiscussion = (text: string, anchorId?: string) => {
addDiscussion(text, anchorId);
};
// Start replying to a discussion
const handleReply = (discussionId: string) => {
setReplyToItem({discussionId});
};
}
```
## Usage Examples
### Basic Discussion Panel
```tsx
import {DiscussionList, CommentItem} from '@sqlrooms/discuss';
import {useStoreWithDiscussion} from '@sqlrooms/discuss';
import {formatTimeRelative} from '@sqlrooms/utils';
const DiscussionPanel = () => {
const discussions = useStoreWithDiscussion(
(state) => state.discuss.config.discussions,
);
return (
);
};
```
### Anchor-Based Discussions
Link discussions to specific data points or UI elements:
```tsx
import {useStoreWithDiscussion} from '@sqlrooms/discuss';
function DataVisualization() {
const addDiscussion = useStoreWithDiscussion(
(state) => state.discuss.addDiscussion,
);
const setHighlightedDiscussionId = useStoreWithDiscussion(
(state) => state.discuss.setHighlightedDiscussionId,
);
// Handle clicking on a data point
const handleDataPointClick = (dataId: string) => {
// Add a discussion linked to this data point
addDiscussion('What do you think about this data point?', dataId);
};
// Highlight related discussion when hovering over data
const handleDataPointHover = (dataId: string) => {
const discussions =
useStoreWithDiscussion.getState().discuss.config.discussions;
const relatedDiscussion = discussions.find((d) => d.anchorId === dataId);
if (relatedDiscussion) {
setHighlightedDiscussionId(relatedDiscussion.id);
}
};
return (
{/* Your data visualization with clickable elements */}
);
}}
/>
);
};
```
### Programmatic Discussion Management
```tsx
import {useStoreWithDiscussion} from '@sqlrooms/discuss';
function DiscussionManager() {
const {
addDiscussion,
removeDiscussion,
addComment,
setReplyToItem,
setEditingItem,
submitEdit,
} = useStoreWithDiscussion((state) => state.discuss);
// Add a new discussion
const createDiscussion = () => {
addDiscussion('New discussion topic', 'optional-anchor-id');
};
// Reply to a discussion
const replyToDiscussion = (discussionId: string) => {
setReplyToItem({discussionId});
// User can now type in the form and call submitEdit
};
// Edit a comment
const editComment = (discussionId: string, commentId: string) => {
setEditingItem({discussionId, commentId});
// User can now edit in the form and call submitEdit
};
// Direct comment addition (bypassing UI state)
const addDirectComment = (discussionId: string, text: string) => {
addComment(discussionId, text);
};
return (
);
}
```
## API Reference
### Types
* `Comment`: Individual comment with id, userId, text, timestamp, and optional parentId
* `Discussion`: Container with id, optional anchorId, rootComment, and array of reply comments
* `DiscussSliceConfig`: Configuration type for the discuss slice
* `DiscussSliceState`: State type including all discussion actions and UI state
### Key Functions
* `createDiscussSlice({ userId })`: Creates the discussion slice for your store
* `createDefaultDiscussConfig()`: Returns default configuration for discussions
* `useStoreWithDiscussion(selector)`: Hook to access discussion state and actions
### Main Actions
* `submitEdit(text)`: Submit based on current UI state (add/reply/edit)
* `addDiscussion(text, anchorId?)`: Add new discussion
* `addComment(discussionId, text, parentId?)`: Add reply to discussion
* `setReplyToItem(item)`: Set reply context for UI
* `setEditingItem(item)`: Set editing context for UI
* `setHighlightedDiscussionId(id)`: Highlight specific discussion
This module integrates seamlessly with the SQLRooms ecosystem and provides a complete foundation for building collaborative discussion features in your applications.
## Type Aliases
* [Comment](type-aliases/Comment.md)
* [Discussion](type-aliases/Discussion.md)
* [DiscussSliceConfig](type-aliases/DiscussSliceConfig.md)
* [DiscussSliceState](type-aliases/DiscussSliceState.md)
* [RoomStateWithDiscussion](type-aliases/RoomStateWithDiscussion.md)
## Variables
* [Comment](variables/Comment.md)
* [Discussion](variables/Discussion.md)
* [DiscussSliceConfig](variables/DiscussSliceConfig.md)
## Functions
* [createDefaultDiscussConfig](functions/createDefaultDiscussConfig.md)
* [createDiscussSlice](functions/createDiscussSlice.md)
* [useStoreWithDiscussion](functions/useStoreWithDiscussion.md)
* [DiscussionList](functions/DiscussionList.md)
* [CommentItem](functions/CommentItem.md)
* [DeleteConfirmDialog](functions/DeleteConfirmDialog.md)
* [DiscussionItem](functions/DiscussionItem.md)
---
---
url: /api/dropzone.md
---
# @sqlrooms/dropzone
This package is part of the SQLRooms framework.
A flexible file upload component for SQLRooms applications that provides drag-and-drop functionality for files. This package makes it easy to handle file uploads with a modern, user-friendly interface.
## Features
* 📁 **Drag and Drop**: Intuitive drag-and-drop file upload interface
* 📋 **File Selection**: Traditional file selection dialog support
* 🔍 **File Validation**: Validate file types and sizes
* 📊 **Upload Progress**: Track and display upload progress
* 🎨 **Customizable**: Flexible styling and configuration options
* 🧩 **React Integration**: Seamless integration with React applications
## Installation
```bash
npm install @sqlrooms/dropzone
# or
yarn add @sqlrooms/dropzone
```
## Basic Usage
### Simple File Dropzone
```tsx
import {FileDropzone} from '@sqlrooms/dropzone';
function MyFileUploader() {
const handleFileDrop = (files) => {
console.log('Files dropped:', files);
// Process the files...
};
return (
);
}
```
### With Custom Styling
```tsx
import {FileDropzone} from '@sqlrooms/dropzone';
function CustomStyledDropzone() {
return (
);
}
```
### With File Type Validation
```tsx
import {FileDropzone} from '@sqlrooms/dropzone';
function DataFileUploader() {
const handleFileDrop = (files) => {
// Process data files...
};
return (
Upload Data Files
Supported formats: CSV, JSON, Excel, Parquet
);
}
```
## Advanced Features
* **Multiple File Upload**: Support for uploading multiple files at once
* **File Preview**: Preview files before uploading
* **Custom Validation**: Define custom validation rules for files
* **Upload Cancellation**: Cancel ongoing uploads
* **Accessibility**: Fully accessible interface with keyboard support
For more information, visit the SQLRooms documentation.
## Functions
* [FileDropzone](functions/FileDropzone.md)
---
---
url: /api/duckdb.md
---
# @sqlrooms/duckdb
A powerful wrapper around DuckDB-WASM that provides React hooks and utilities for working with DuckDB in browser environments.
## Features
### React Integration & Type Safety
* **React Hooks**: Seamless integration with React applications via `useSql`
* **Runtime Validation**: Optional Zod schema validation for query results with type transformations
* **Typed Row Accessors**: Type-safe row access with validation and multiple iteration methods
### Data Management
* **File Operations**: Import data from various file formats (CSV, JSON, Parquet) with auto-detection
* **Arrow Integration**: Work directly with Apache Arrow tables for efficient columnar data processing
* **Schema Management**: Comprehensive database, schema, and table discovery and management
* **Qualified Table Names**: Full support for `database.schema.table` naming convention
### Performance & Operations
* **Query Deduplication**: Automatic deduplication of identical running queries to prevent duplicate execution
* **Query Cancellation**: Cancel running queries with full composability support via `QueryHandle` interface ([learn more](https://sqlrooms.org/query-cancellation))
* **Data Export**: Export query results to CSV files with pagination for large datasets
* **Batch Processing**: Handle large datasets efficiently with built-in pagination support
## Installation
```bash
npm install @sqlrooms/duckdb
```
## Basic Usage
### Using the SQL Hook
```tsx
import {useSql} from '@sqlrooms/duckdb';
function UserList() {
// Basic usage with TypeScript types
const {data, isLoading, error} = useSql<{id: number; name: string}>({
query: 'SELECT id, name FROM users',
});
if (isLoading) return
Loading...
;
if (error) return
Error: {error.message}
;
if (!data) return null;
return (
{Array.from(data.rows()).map((user) => (
{user.name}
))}
);
}
```
For more information and examples on using the `useSql` hook, see the [useSql API documentation](/api/duckdb/functions/useSql).
### Using Zod for Runtime Validation
```tsx
import {useSql} from '@sqlrooms/duckdb';
import {z} from 'zod';
const userSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
created_at: z.string().transform((str) => new Date(str)),
});
function ValidatedUserList() {
const {data, isLoading, error} = useSql(userSchema, {
query: 'SELECT id, name, email, created_at FROM users',
});
if (isLoading) return
Loading...
;
if (error) {
if (error instanceof z.ZodError) {
return
);
}
```
### Accessing the Underlying Arrow Table and Schema
You can access the underlying Arrow table and schema of a `useSql()` query result. This is especially useful if you want to pass the data to a library that expect an Apache Arrow Table as input without additional data transformation:
```tsx
import {useSql} from '@sqlrooms/duckdb';
function ArrowTableSchemaExample() {
const {data, isLoading, error} = useSql({
query: 'SELECT id, name FROM users',
});
if (isLoading) return
);
}
```
### Working with Qualified Table Names
```tsx
import {makeQualifiedTableName} from '@sqlrooms/duckdb';
// Support for database.schema.table naming
const qualifiedTable = makeQualifiedTableName({
database: 'mydb',
schema: 'public',
table: 'users',
});
// Use with table operations
await createTableFromQuery(qualifiedTable, 'SELECT * FROM source_table');
await dropTable(qualifiedTable);
const tableExists = await checkTableExists(qualifiedTable);
```
## Loading Data from Files
### Using Load Functions Directly
```tsx
import {loadCSV, loadJSON, loadParquet, loadObjects} from '@sqlrooms/duckdb';
function DataLoader() {
const getConnector = useRoomStore((state) => state.db.getConnector);
const handleLoadCSV = async (file: File) => {
const connector = await getConnector();
// Generate SQL to load CSV file
const sql = loadCSV('my_table', file.name, {
auto_detect: true,
replace: true,
});
// Execute the load operation
await connector.query(sql).result;
};
const handleLoadObjects = async () => {
const connector = await getConnector();
const data = [
{id: 1, name: 'Alice'},
{id: 2, name: 'Bob'},
];
// Generate SQL to load objects
const sql = loadObjects('users', data, {replace: true});
await connector.query(sql).result;
};
return (
{
if (e.target.files?.[0]) handleLoadCSV(e.target.files[0]);
}}
/>
);
}
```
### Using the Connector Directly
```tsx
function AdvancedDataLoader() {
const connector = useRoomStore((state) => state.db.connector);
const handleFileUpload = async (file: File) => {
// Load file directly using the connector
await connector.loadFile(file, 'uploaded_data', {
method: 'auto', // Auto-detect file type
replace: true,
temp: false,
});
};
const handleLoadArrowTable = async (arrowTable: arrow.Table) => {
// Load Arrow table directly
await connector.loadArrow(arrowTable, 'arrow_data');
};
return (
{
if (e.target.files?.[0]) handleFileUpload(e.target.files[0]);
}}
/>
);
}
```
## Exporting Data to CSV
```tsx
import {useExportToCsv} from '@sqlrooms/duckdb';
function ExportButton() {
const {exportToCsv} = useExportToCsv();
const handleExport = async () => {
await exportToCsv('SELECT * FROM users ORDER BY name', 'users_export.csv');
};
return ;
}
```
## Low-Level DuckDB Access
### Basic direct usage
```tsx
async function executeCustomQuery() {
// Grab the connector directly (no React hook necessary inside plain TS)
const connector = useRoomStore((state) => state.db.connector);
// QueryHandle is promise-like – await it directly
const result = await connector.query('SELECT COUNT(*) AS count FROM users');
// Inspect Arrow table
const count = result.getChildAt(0)?.get(0);
console.log(`Total users: ${count}`);
}
```
### Cancellation examples
```tsx
async function cancelExample() {
const connector = useRoomStore((state) => state.db.connector);
// 1. Manual cancel via the handle
const query = connector.query('SELECT * FROM large_table');
setTimeout(() => h.cancel(), 2000); // cancel after 2 s
await query; // throws if cancelled
// 2. Composable cancellation – many queries, one controller
const controller = new AbortController();
const q1 = connector.query('SELECT 1', {signal: controller.signal});
const q2 = connector.query('SELECT 2', {signal: controller.signal});
controller.abort(); // cancels q1 & q2
await Promise.allSettled([q1, q2]);
}
```
### Advanced operations with the Zustand store
```tsx
function AdvancedOperations() {
const executeSql = useRoomStore((s) => s.db.executeSql);
const sqlSelectToJson = useRoomStore((s) => s.db.sqlSelectToJson);
const checkTableExists = useRoomStore((s) => s.db.checkTableExists);
const handleAdvancedQuery = async () => {
// Cached execution with deduplication
const query = await executeSql('SELECT * FROM users LIMIT 10');
if (query) {
const rows = await query; // await handle directly
console.log('Query result:', rows);
}
// Parse SQL to JSON (analysis tool)
const parsed = await sqlSelectToJson('SELECT id, name FROM users');
console.log('Parsed query:', parsed);
// Safety check before destructive operations
const exists = await checkTableExists('users');
console.log('Table exists:', exists);
};
return ;
}
```
For more information, visit the SQLRooms documentation.
## Enumerations
* [DuckDBAccessMode](enumerations/DuckDBAccessMode.md)
## Interfaces
* [DuckDBConfig](interfaces/DuckDBConfig.md)
* [DuckDBBundles](interfaces/DuckDBBundles.md)
* [BaseDuckDbConnectorOptions](interfaces/BaseDuckDbConnectorOptions.md)
* [BaseDuckDbConnectorImpl](interfaces/BaseDuckDbConnectorImpl.md)
* [QueryOptions](interfaces/QueryOptions.md)
* [DuckDbConnector](interfaces/DuckDbConnector.md)
* [WasmDuckDbConnector](interfaces/WasmDuckDbConnector.md)
* [TypedRowAccessor](interfaces/TypedRowAccessor.md)
* [UseSqlQueryResult](interfaces/UseSqlQueryResult.md)
## Type Aliases
* [DuckDbSliceConfig](type-aliases/DuckDbSliceConfig.md)
* [SchemaAndDatabase](type-aliases/SchemaAndDatabase.md)
* [DuckDbSliceState](type-aliases/DuckDbSliceState.md)
* [QueryHandle](type-aliases/QueryHandle.md)
* [QualifiedTableName](type-aliases/QualifiedTableName.md)
* [TableColumn](type-aliases/TableColumn.md)
* [DataTable](type-aliases/DataTable.md)
* [ColumnTypeCategory](type-aliases/ColumnTypeCategory.md)
* [DbSchemaNode](type-aliases/DbSchemaNode.md)
* [NodeObject](type-aliases/NodeObject.md)
* [ColumnNodeObject](type-aliases/ColumnNodeObject.md)
* [TableNodeObject](type-aliases/TableNodeObject.md)
* [SchemaNodeObject](type-aliases/SchemaNodeObject.md)
* [DatabaseNodeObject](type-aliases/DatabaseNodeObject.md)
* [~~DuckConn~~](type-aliases/DuckConn.md)
* [~~DuckDb~~](type-aliases/DuckDb.md)
* [~~DuckDbQueryResult~~](type-aliases/DuckDbQueryResult.md)
* [SpatialLoadFileOptions](type-aliases/SpatialLoadFileOptions.md)
* [LoadFileOptions](type-aliases/LoadFileOptions.md)
## Variables
* [DuckDbSliceConfig](variables/DuckDbSliceConfig.md)
* [SpatialLoadFileOptions](variables/SpatialLoadFileOptions.md)
* [LoadFileOptions](variables/LoadFileOptions.md)
## Functions
* [createDefaultDuckDbConfig](functions/createDefaultDuckDbConfig.md)
* [createDuckDbSlice](functions/createDuckDbSlice.md)
* [useStoreWithDuckDb](functions/useStoreWithDuckDb.md)
* [arrowTableToJson](functions/arrowTableToJson.md)
* [createBaseDuckDbConnector](functions/createBaseDuckDbConnector.md)
* [createWasmDuckDbConnector](functions/createWasmDuckDbConnector.md)
* [createWebSocketDuckDbConnector](functions/createWebSocketDuckDbConnector.md)
* [createDuckDbConnector](functions/createDuckDbConnector.md)
* [isWasmDuckDbConnector](functions/isWasmDuckDbConnector.md)
* [load](functions/load.md)
* [loadCSV](functions/loadCSV.md)
* [loadJSON](functions/loadJSON.md)
* [loadParquet](functions/loadParquet.md)
* [loadSpatial](functions/loadSpatial.md)
* [loadObjects](functions/loadObjects.md)
* [isQualifiedTableName](functions/isQualifiedTableName.md)
* [makeQualifiedTableName](functions/makeQualifiedTableName.md)
* [escapeVal](functions/escapeVal.md)
* [escapeId](functions/escapeId.md)
* [isNumericDuckType](functions/isNumericDuckType.md)
* [getColValAsNumber](functions/getColValAsNumber.md)
* [getSqlErrorWithPointer](functions/getSqlErrorWithPointer.md)
* [splitSqlStatements](functions/splitSqlStatements.md)
* [sanitizeQuery](functions/sanitizeQuery.md)
* [makeLimitQuery](functions/makeLimitQuery.md)
* [useExportToCsv](functions/useExportToCsv.md)
* [getDuckDbTypeCategory](functions/getDuckDbTypeCategory.md)
* [getArrowColumnTypeCategory](functions/getArrowColumnTypeCategory.md)
* [createTypedRowAccessor](functions/createTypedRowAccessor.md)
* [useDuckDb](functions/useDuckDb.md)
* [useSql](functions/useSql.md)
* [~~useDuckDbQuery~~](functions/useDuckDbQuery.md)
* [isSpatialLoadFileOptions](functions/isSpatialLoadFileOptions.md)
---
---
url: /api/duckdb-config.md
---
# @sqlrooms/duckdb-config
A central configuration and type definitions package that maintains base DuckDB configuration schemas and Zod schema definitions for SQLRooms. It provides TypeScript types and interfaces along with essential constants and utilities used for managing DuckDB state.
## Features
* 📝 **DuckDB Configuration**: Define and manage room DuckDB configuration schemas.
* 🔍 **Type Safety**: Strong TypeScript typing for DuckDB configuration objects.
* ✅ **Validation**: Zod schemas for runtime validation of DuckDB configurations.
## Installation
```bash
npm install @sqlrooms/duckdb-config
# or
yarn add @sqlrooms/duckdb-config
```
## Basic Usage
### Working with DuckDB Configuration
```tsx
import {
DuckDbSliceConfig,
createDefaultDuckDbConfig,
} from '@sqlrooms/duckdb-config';
// Create a new DuckDB configuration
const duckDbConfig: DuckDbSliceConfig = createDefaultDuckDbConfig();
// This is then used as part of a bigger room configuration.
// The `RoomConfig` for a room is typically a composition of slice configurations.
// For example:
//
// import {SqlEditorSliceConfig} from '@sqlrooms/sql-editor-config';
//
// type RoomConfig = DuckDbSliceConfig & SqlEditorSliceConfig;
```
## Advanced Features
* **Schema Extensions**: Extend base schemas for custom room types
* **Configuration Validation**: Validate configurations at runtime
* **Serialization**: Convert configurations to/from JSON for storage
For more information, visit the SQLRooms documentation.
```
```
## Type Aliases
* [DuckDbSliceConfig](type-aliases/DuckDbSliceConfig.md)
## Variables
* [DuckDbSliceConfig](variables/DuckDbSliceConfig.md)
## Functions
* [createDefaultDuckDbConfig](functions/createDefaultDuckDbConfig.md)
---
---
url: /api/layout.md
---
# @sqlrooms/layout
This package is part of the SQLRooms framework and provides flexible layout components for building complex, resizable, and draggable interfaces.
## Overview
The `@sqlrooms/layout` package offers a set of components and utilities for creating dynamic, multi-pane layouts in SQLRooms applications. It's primarily built around the [react-mosaic](https://nomcopter.github.io/react-mosaic/) library, which provides a powerful windowing system similar to the one found in advanced IDEs.
> **Note:** This package uses [react-mosaic](https://nomcopter.github.io/react-mosaic/) which should not be confused with [uwdata/mosaic](https://github.com/uwdata/mosaic) used in the [`@sqlrooms/mosaic`](/api/mosaic/) package for data visualization purposes.
## Installation
```bash
npm install @sqlrooms/layout
```
## Mosaic Tree Structure
The mosaic layout is defined by a tree structure where each node is either a string (representing a panel ID) or an object with `direction`, `first`, `second`, and optional `splitPercentage` properties. Here's an example of how a mosaic tree might look:
```tsx
// Simple two-panel layout with 30/70 split
const simpleMosaicTree = {
direction: 'row',
first: 'data-sources', // Left panel (30% width)
second: 'main', // Right panel (70% width)
splitPercentage: 30,
};
// More complex nested layout
const complexMosaicTree = {
direction: 'row',
first: 'data-sources', // Left panel
second: {
// Right side contains a nested layout
direction: 'column',
first: 'main', // Top panel
second: {
// Bottom contains another nested layout
direction: 'row',
first: 'sql-editor',
second: 'visualization',
splitPercentage: 50,
},
splitPercentage: 60,
},
splitPercentage: 20,
};
```
## Components
### MosaicLayout
A wrapper around the `Mosaic` component from react-mosaic-component that provides a customized look and feel consistent with SQLRooms styling.
```tsx
import {MosaicLayout} from '@sqlrooms/layout';
// Example usage
}
value={yourMosaicTree}
onChange={handleLayoutChange}
/>;
```
### MosaicTile
A component for rendering individual tiles within the mosaic layout.
## Utility Functions
The package provides several utility functions for working with mosaic layouts:
* `makeMosaicStack`: Creates a stack of mosaic nodes with specified weights and direction
* `visitMosaicLeafNodes`: Traverses all leaf nodes in a mosaic tree
* `getVisibleMosaicLayoutPanels`: Gets an array of all visible panel IDs
* `findMosaicNodePathByKey`: Finds the path to a specific node by its key
* `removeMosaicNodeByKey`: Removes a node from the mosaic tree by its key
## Learn More
For more information about the underlying react-mosaic library, visit:
* [react-mosaic documentation](https://nomcopter.github.io/react-mosaic/)
* [react-mosaic GitHub repository](https://github.com/nomcopter/react-mosaic)
## License
MIT
## Type Aliases
* [LayoutTypes](type-aliases/LayoutTypes.md)
* [MosaicLayoutDirection](type-aliases/MosaicLayoutDirection.md)
* [MosaicLayoutParent](type-aliases/MosaicLayoutParent.md)
* [MosaicLayoutNodeKey](type-aliases/MosaicLayoutNodeKey.md)
* [MosaicLayoutNode](type-aliases/MosaicLayoutNode.md)
* [MosaicLayoutConfig](type-aliases/MosaicLayoutConfig.md)
* [LayoutConfig](type-aliases/LayoutConfig.md)
* [RoomPanelInfo](type-aliases/RoomPanelInfo.md)
* [LayoutSliceConfig](type-aliases/LayoutSliceConfig.md)
* [LayoutSliceState](type-aliases/LayoutSliceState.md)
## Variables
* [MAIN\_VIEW](variables/MAIN_VIEW.md)
* [LayoutTypes](variables/LayoutTypes.md)
* [~~DEFAULT\_MOSAIC\_LAYOUT~~](variables/DEFAULT_MOSAIC_LAYOUT.md)
* [MosaicLayoutDirection](variables/MosaicLayoutDirection.md)
* [MosaicLayoutParent](variables/MosaicLayoutParent.md)
* [MosaicLayoutNodeKey](variables/MosaicLayoutNodeKey.md)
* [MosaicLayoutNode](variables/MosaicLayoutNode.md)
* [MosaicLayoutConfig](variables/MosaicLayoutConfig.md)
* [LayoutConfig](variables/LayoutConfig.md)
* [LayoutSliceConfig](variables/LayoutSliceConfig.md)
## Functions
* [createDefaultMosaicLayout](functions/createDefaultMosaicLayout.md)
* [isMosaicLayoutParent](functions/isMosaicLayoutParent.md)
* [createDefaultLayoutConfig](functions/createDefaultLayoutConfig.md)
* [createLayoutSlice](functions/createLayoutSlice.md)
* [useStoreWithLayout](functions/useStoreWithLayout.md)
* [MosaicLayout](functions/MosaicLayout.md)
* [makeMosaicStack](functions/makeMosaicStack.md)
* [visitMosaicLeafNodes](functions/visitMosaicLeafNodes.md)
* [getVisibleMosaicLayoutPanels](functions/getVisibleMosaicLayoutPanels.md)
* [findMosaicNodePathByKey](functions/findMosaicNodePathByKey.md)
* [removeMosaicNodeByKey](functions/removeMosaicNodeByKey.md)
---
---
url: /api/layout-config.md
---
# @sqlrooms/layout-config
A central configuration and type definitions package that maintains base layout configuration schemas and Zod schema definitions for SQLRooms. It provides TypeScript types and interfaces along with essential constants and utilities used for managing layouts.
## Features
* 📝 **Layout Configuration**: Define and manage room layout configuration schemas for Mosaic layouts
* 🔍 **Type Safety**: Strong TypeScript typing for layout configuration objects
* ✅ **Validation**: Zod schemas for runtime validation of layout configurations
## Installation
```bash
npm install @sqlrooms/layout-config
# or
yarn add @sqlrooms/layout-config
```
## Basic Usage
### Working with Mosaic Layout Configuration
```tsx
import {
MosaicLayoutConfig,
LayoutConfig,
MAIN_VIEW,
} from '@sqlrooms/layout-config';
// Create a new room configuration
const layoutConfig: MosaicLayoutConfig = {
type: 'mosaic',
nodes: {
direction: 'row',
first: MAIN_VIEW,
second: {
direction: 'column',
first: 'files',
second: 'tables',
},
},
};
// This can be part of a bigger room configuration
interface RoomConfig {
// ... other properties
layout: LayoutConfig;
}
```
## Advanced Features
* **Schema Extensions**: Extend base schemas for custom room types
* **Configuration Validation**: Validate configurations at runtime
* **Serialization**: Convert configurations to/from JSON for storage
For more information, visit the SQLRooms documentation.
```
```
## Type Aliases
* [LayoutTypes](type-aliases/LayoutTypes.md)
* [MosaicLayoutDirection](type-aliases/MosaicLayoutDirection.md)
* [MosaicLayoutParent](type-aliases/MosaicLayoutParent.md)
* [MosaicLayoutNodeKey](type-aliases/MosaicLayoutNodeKey.md)
* [MosaicLayoutNode](type-aliases/MosaicLayoutNode.md)
* [MosaicLayoutConfig](type-aliases/MosaicLayoutConfig.md)
* [LayoutConfig](type-aliases/LayoutConfig.md)
## Variables
* [MAIN\_VIEW](variables/MAIN_VIEW.md)
* [LayoutTypes](variables/LayoutTypes.md)
* [~~DEFAULT\_MOSAIC\_LAYOUT~~](variables/DEFAULT_MOSAIC_LAYOUT.md)
* [MosaicLayoutDirection](variables/MosaicLayoutDirection.md)
* [MosaicLayoutParent](variables/MosaicLayoutParent.md)
* [MosaicLayoutNodeKey](variables/MosaicLayoutNodeKey.md)
* [MosaicLayoutNode](variables/MosaicLayoutNode.md)
* [MosaicLayoutConfig](variables/MosaicLayoutConfig.md)
* [LayoutConfig](variables/LayoutConfig.md)
## Functions
* [createDefaultMosaicLayout](functions/createDefaultMosaicLayout.md)
* [isMosaicLayoutParent](functions/isMosaicLayoutParent.md)
---
---
url: /api/monaco-editor.md
---
# @sqlrooms/monaco-editor
This package is part of the SQLRooms framework.
# Monaco Editor
Monaco Editor components for SQLRooms, including specialized editors for JSON.
## Installation
```bash
npm install @sqlrooms/monaco-editor
```
## Components
### MonacoEditor
A base Monaco Editor component with common functionality.
```tsx
import {MonacoEditor} from '@sqlrooms/monaco-editor';
function MyComponent() {
return (
console.log(value)}
/>
);
}
```
### JsonMonacoEditor
A specialized Monaco Editor for editing JSON with schema validation.
```tsx
import {JsonMonacoEditor} from '@sqlrooms/monaco-editor';
function MyJsonEditor() {
const schema = {
type: 'object',
properties: {
name: {type: 'string'},
age: {type: 'number'},
},
required: ['name'],
};
return (
console.log(value)}
/>
);
}
```
### Configuring the loader for offline use
By default, the editor loads its sources from a CDN. To use the editor in an
offline environment, you need to bundle `monaco-editor` with your application.
You can do this with the `configureMonacoLoader` utility. This function is a
thin wrapper around the [`loader.config` function](https://github.com/suren-atoyan/monaco-react#loader-config)
and sets up `self.MonacoEnvironment` automatically when web workers are passed.
Here's an example of how to configure the loader to use bundled workers with
Vite (note the `?worker` suffix):
```ts
import {configureMonacoLoader} from '@sqlrooms/monaco-editor';
import * as monaco from 'monaco-editor';
import editorWorker from 'monaco-editor/esm/vs/editor/editor.worker?worker';
import jsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import tsWorker from 'monaco-editor/esm/vs/language/typescript/ts.worker?worker';
// Use the monaco-editor package instead of a CDN
configureMonacoLoader({
monaco,
workers: {
default: editorWorker,
json: jsonWorker,
typescript: tsWorker,
javascript: tsWorker,
},
});
```
You can also use `configureMonacoLoader` to specify a custom path to the
editor's sources, for example, if you are hosting them on a different CDN:
```ts
// configureMonacoLoader({paths: {vs: 'https://unpkg.com/monaco-editor/min/vs'}});
```
## Props
### MonacoEditor Props
| Prop | Type | Default | Description |
| --------- | -------------------- | ------------ | ---------------------------------------- |
| className | string | '' | CSS class name for the editor container |
| language | string | 'javascript' | The language of the editor |
| theme | 'vs-dark' | 'light' | 'vs-dark' | The theme of the editor |
| value | string | '' | The value of the editor |
| readOnly | boolean | false | Whether the editor is read-only |
| options | object | {} | Additional options for the editor |
| onMount | function | - | Callback when the editor is mounted |
| onChange | function | - | Callback when the editor content changes |
### JsonMonacoEditor Props
Extends `MonacoEditorProps` with:
| Prop | Type | Default | Description |
| ------ | ---------------- | ------- | ----------------------------------- |
| schema | object | - | The JSON schema to validate against |
| value | string | object | '' | The JSON value to edit |
## License
MIT
## Interfaces
* [JsonMonacoEditorProps](interfaces/JsonMonacoEditorProps.md)
* [MonacoEditorProps](interfaces/MonacoEditorProps.md)
* [LoaderWorkers](interfaces/LoaderWorkers.md)
* [MonacoLoaderOptions](interfaces/MonacoLoaderOptions.md)
## Type Aliases
* [LoaderConfig](type-aliases/LoaderConfig.md)
## Variables
* [DEFAULT\_CDN\_PATH](variables/DEFAULT_CDN_PATH.md)
## Functions
* [JsonMonacoEditor](functions/JsonMonacoEditor.md)
* [MonacoEditor](functions/MonacoEditor.md)
* [configureMonacoLoader](functions/configureMonacoLoader.md)
* [ensureMonacoLoaderConfigured](functions/ensureMonacoLoaderConfigured.md)
* [hslToHex](functions/hslToHex.md)
* [getCssColor](functions/getCssColor.md)
* [getMonospaceFont](functions/getMonospaceFont.md)
---
---
url: /api/mosaic.md
---
# @sqlrooms/mosaic
This package is part of the SQLRooms framework. It provides React components and hooks for integrating [Mosaic](https://idl.uw.edu/mosaic/) - a visualization library for data exploration and analysis - into SQLRooms applications.
## Overview
Mosaic is a JavaScript library for data visualization and analysis developed by the [Interactive Data Lab (IDL)](https://idl.uw.edu/) at the University of Washington. It combines the expressiveness of declarative visualization grammars with the power of reactive programming and SQL queries.
One of Mosaic's powerful features is its cross-filtering capability powered by DuckDB, allowing users to interactively filter and explore large datasets with millions of records directly in the browser. This enables creating interactive dashboards where selections in one chart automatically filter data in other charts. For an example of this functionality, see the [Cross-Filter Flights demo](https://idl.uw.edu/mosaic/examples/flights-200k.html) which demonstrates interactive filtering across multiple visualizations of a 200,000-record flight dataset.
This package provides:
* React components for rendering Vega-Lite charts using Mosaic
* Hooks for integrating Mosaic with DuckDB in SQLRooms applications
* Utilities for working with Mosaic specifications
## Installation
```bash
npm install @sqlrooms/mosaic
```
## Usage
### VgPlotChart Component
The `VgPlotChart` component renders a Vega-Lite chart using the Mosaic library:
```tsx
import {VgPlotChart, Spec} from '@sqlrooms/mosaic';
const spec: Spec = {
// Your Vega-Lite specification
};
function MyChart() {
return ;
}
```
### useMosaic Hook
The `useMosaic` hook provides access to the Mosaic connector for DuckDB:
```tsx
import {useMosaic} from '@sqlrooms/mosaic';
function MyComponent() {
const {isMosaicLoading, mosaicConnector} = useMosaic();
if (isMosaicLoading) {
return
Loading...
;
}
// Use mosaicConnector to interact with DuckDB through Mosaic
return
Mosaic is ready!
;
}
```
## Resources
* [Mosaic Documentation](https://idl.uw.edu/mosaic/)
* [Cross-Filter Flights Demo](https://idl.uw.edu/mosaic/examples/flights-200k.html)
* [Vega-Lite Documentation](https://vega.github.io/vega-lite/)
* [DuckDB Documentation](https://duckdb.org/docs/)
## License
MIT
## Type Aliases
* [Spec](type-aliases/Spec.md)
## Functions
* [VgPlotChart](functions/VgPlotChart.md)
* [useMosaic](functions/useMosaic.md)
---
---
url: /api/motherduck.md
---
# @sqlrooms/motherduck
[MotherDuck](https://motherduck.com/) is a managed DuckDB-in-the-cloud service that enables you to run DuckDB queries both in your browser and in the cloud.
This package exposes a `createWasmMotherDuckDbConnector` function, which allows SQLRooms to connect to MotherDuck.
The connector is implemented using the [`@motherduck/wasm-client`](https://motherduck.com/docs/sql-reference/wasm-client/) library which is a customized version of [`@duckdb/duckdb-wasm`](https://github.com/duckdb/duckdb-wasm/tree/main/packages/duckdb-wasm) capable of querying MotherDuck datasets in the cloud from the browser.
## Example
See [`MotherDuck Cloud Query Editor`](/examples#motherduck-cloud-query-editor) for a usage example.
## Interfaces
* [WasmMotherDuckDbConnectorOptions](interfaces/WasmMotherDuckDbConnectorOptions.md)
* [WasmMotherDuckDbConnector](interfaces/WasmMotherDuckDbConnector.md)
## Functions
* [isWasmMotherDuckDbConnector](functions/isWasmMotherDuckDbConnector.md)
* [createWasmMotherDuckDbConnector](functions/createWasmMotherDuckDbConnector.md)
---
---
url: /api/recharts.md
---
# @sqlrooms/recharts
A package that provides Recharts integration for SQLRooms based on [shadcn Chart component](https://ui.shadcn.com/docs/components/chart).
## Namespaces
* [CartesianGrid](namespaces/CartesianGrid/index.md)
* [Customized](namespaces/Customized/index.md)
* [Label](namespaces/Label/index.md)
* [LabelList](namespaces/LabelList/index.md)
## Classes
* [Area](classes/Area.md)
* [Bar](classes/Bar.md)
* [Brush](classes/Brush.md)
* [CartesianAxis](classes/CartesianAxis.md)
* [ErrorBar](classes/ErrorBar.md)
* [Line](classes/Line.md)
* [ReferenceArea](classes/ReferenceArea.md)
* [ReferenceDot](classes/ReferenceDot.md)
* [ReferenceLine](classes/ReferenceLine.md)
* [Scatter](classes/Scatter.md)
* [XAxis](classes/XAxis.md)
* [YAxis](classes/YAxis.md)
* [ZAxis](classes/ZAxis.md)
* [Sankey](classes/Sankey.md)
* [Treemap](classes/Treemap.md)
* [DefaultLegendContent](classes/DefaultLegendContent.md)
* [Legend](classes/Legend.md)
* [Tooltip](classes/Tooltip.md)
* [Funnel](classes/Funnel.md)
* [Pie](classes/Pie.md)
* [PolarAngleAxis](classes/PolarAngleAxis.md)
* [PolarRadiusAxis](classes/PolarRadiusAxis.md)
* [Radar](classes/Radar.md)
* [RadialBar](classes/RadialBar.md)
## Interfaces
* [ZAxisProps](interfaces/ZAxisProps.md)
* [TreemapProps](interfaces/TreemapProps.md)
* [DefaultTooltipContentProps](interfaces/DefaultTooltipContentProps.md)
* [ResponsiveContainerProps](interfaces/ResponsiveContainerProps.md)
* [PieLabelRenderProps](interfaces/PieLabelRenderProps.md)
## Type Aliases
* [AreaProps](type-aliases/AreaProps.md)
* [BarProps](type-aliases/BarProps.md)
* [BrushProps](type-aliases/BrushProps.md)
* [CartesianAxisProps](type-aliases/CartesianAxisProps.md)
* [CartesianGridProps](type-aliases/CartesianGridProps.md)
* [ErrorBarProps](type-aliases/ErrorBarProps.md)
* [LineProps](type-aliases/LineProps.md)
* [ReferenceAreaProps](type-aliases/ReferenceAreaProps.md)
* [ReferenceDotProps](type-aliases/ReferenceDotProps.md)
* [ReferenceLineProps](type-aliases/ReferenceLineProps.md)
* [ScatterProps](type-aliases/ScatterProps.md)
* [XAxisProps](type-aliases/XAxisProps.md)
* [YAxisProps](type-aliases/YAxisProps.md)
* [CellProps](type-aliases/CellProps.md)
* [CustomizedProps](type-aliases/CustomizedProps.md)
* [DefaultLegendContentProps](type-aliases/DefaultLegendContentProps.md)
* [LabelProps](type-aliases/LabelProps.md)
* [LabelListProps](type-aliases/LabelListProps.md)
* [LegendProps](type-aliases/LegendProps.md)
* [TextProps](type-aliases/TextProps.md)
* [TooltipProps](type-aliases/TooltipProps.md)
* [LayerProps](type-aliases/LayerProps.md)
* [SurfaceProps](type-aliases/SurfaceProps.md)
* [FunnelProps](type-aliases/FunnelProps.md)
* [PieLabel](type-aliases/PieLabel.md)
* [PieProps](type-aliases/PieProps.md)
* [PolarAngleAxisProps](type-aliases/PolarAngleAxisProps.md)
* [PolarGridProps](type-aliases/PolarGridProps.md)
* [PolarRadiusAxisProps](type-aliases/PolarRadiusAxisProps.md)
* [RadarProps](type-aliases/RadarProps.md)
* [RadialBarProps](type-aliases/RadialBarProps.md)
* [CrossProps](type-aliases/CrossProps.md)
* [CurveProps](type-aliases/CurveProps.md)
* [DotProps](type-aliases/DotProps.md)
* [PolygonProps](type-aliases/PolygonProps.md)
* [RectangleProps](type-aliases/RectangleProps.md)
* [SectorProps](type-aliases/SectorProps.md)
* [SymbolsProps](type-aliases/SymbolsProps.md)
* [TrapezoidProps](type-aliases/TrapezoidProps.md)
* [LegendType](type-aliases/LegendType.md)
* [ChartConfig](type-aliases/ChartConfig.md)
## Variables
* [Global](variables/Global.md)
* [ChartTooltip](variables/ChartTooltip.md)
* [ChartLegend](variables/ChartLegend.md)
## Functions
* [CartesianGrid](functions/CartesianGrid.md)
* [AreaChart](functions/AreaChart.md)
* [BarChart](functions/BarChart.md)
* [ComposedChart](functions/ComposedChart.md)
* [FunnelChart](functions/FunnelChart.md)
* [LineChart](functions/LineChart.md)
* [PieChart](functions/PieChart.md)
* [RadarChart](functions/RadarChart.md)
* [RadialBarChart](functions/RadialBarChart.md)
* [ScatterChart](functions/ScatterChart.md)
* [SunburstChart](functions/SunburstChart.md)
* [Cell](functions/Cell.md)
* [Customized](functions/Customized.md)
* [DefaultTooltipContent](functions/DefaultTooltipContent.md)
* [Label](functions/Label.md)
* [LabelList](functions/LabelList.md)
* [ResponsiveContainer](functions/ResponsiveContainer.md)
* [Text](functions/Text.md)
* [Layer](functions/Layer.md)
* [Surface](functions/Surface.md)
* [PolarGrid](functions/PolarGrid.md)
* [Cross](functions/Cross.md)
* [Curve](functions/Curve.md)
* [Dot](functions/Dot.md)
* [Polygon](functions/Polygon.md)
* [Rectangle](functions/Rectangle.md)
* [Sector](functions/Sector.md)
* [Symbols](functions/Symbols.md)
* [Trapezoid](functions/Trapezoid.md)
* [ChartContainer](functions/ChartContainer.md)
* [ChartStyle](functions/ChartStyle.md)
* [ChartTooltipContent](functions/ChartTooltipContent.md)
* [ChartLegendContent](functions/ChartLegendContent.md)
---
---
url: /api/room-config.md
---
# @sqlrooms/room-config
A central configuration and type definitions package that maintains base room configuration schemas and Zod schema definitions. It provides TypeScript types and interfaces along with essential constants and utilities used throughout the framework.
## Features
* 📝 **Room Configuration**: Define and manage room configuration schemas
* 🔍 **Type Safety**: Strong TypeScript typing for configuration objects
* ✅ **Validation**: Zod schemas for runtime validation of configuration
## Installation
```bash
npm install @sqlrooms/room-config
# or
yarn add @sqlrooms/room-config
```
## Basic Usage
### Working with Base Room Configuration
```tsx
import {BaseRoomConfig} from '@sqlrooms/room-config';
// Create a new room configuration
const roomConfig: BaseRoomConfig = {
name: 'My SQL Room',
description: 'A data analysis room using SQLRooms',
version: '1.0.0',
settings: {
theme: 'dark',
// Other settings...
},
};
// Access configuration properties
console.log(roomConfig.name); // 'My SQL Room'
```
### Persisting Room Configuration
Room configuration is designed to be saved and restored between sessions. Here's how to use it with Zustand's persist middleware:
```tsx
import {persist} from 'zustand/middleware';
import {createRoomStore, createRoomShellSlice} from '@sqlrooms/room-shell';
import {BaseRoomConfig} from '@sqlrooms/room-config';
// Create a store with persistence for configuration
const {useRoomStore} = createRoomStore(
persist(
(set, get, store) => ({
...createRoomShellSlice({
// Config is stored at the root level of state for persisting the app state
config: {
title: 'My Room',
// Other configuration properties
},
// Room object contains panels and runtime-only state
room: {
panels: {
// Panel definitions
},
},
})(set, get, store),
}),
{
name: 'room-config-storage',
// Only persist the configuration part of the state
partialize: (state) => ({
config: state.config,
}),
},
),
);
// Access the config in components
function ConfigComponent() {
// Config is accessed directly from state, not from state.room.config
const config = useRoomStore((state) => state.config);
return
{config.title}
;
}
```
## Advanced Features
* **Schema Extensions**: Extend base schemas for custom room types
* **Configuration Validation**: Validate configurations at runtime
* **Serialization**: Convert configurations to/from JSON for storage
For more information, visit the SQLRooms documentation.
```
```
## Type Aliases
* [LayoutTypes](type-aliases/LayoutTypes.md)
* [MosaicLayoutDirection](type-aliases/MosaicLayoutDirection.md)
* [MosaicLayoutParent](type-aliases/MosaicLayoutParent.md)
* [MosaicLayoutNodeKey](type-aliases/MosaicLayoutNodeKey.md)
* [MosaicLayoutNode](type-aliases/MosaicLayoutNode.md)
* [MosaicLayoutConfig](type-aliases/MosaicLayoutConfig.md)
* [LayoutConfig](type-aliases/LayoutConfig.md)
* [BaseRoomConfig](type-aliases/BaseRoomConfig.md)
* [DataSourceTypes](type-aliases/DataSourceTypes.md)
* [BaseDataSource](type-aliases/BaseDataSource.md)
* [FileDataSource](type-aliases/FileDataSource.md)
* [UrlDataSource](type-aliases/UrlDataSource.md)
* [SqlQueryDataSource](type-aliases/SqlQueryDataSource.md)
* [DataSource](type-aliases/DataSource.md)
* [LoadFile](type-aliases/LoadFile.md)
* [StandardLoadOptions](type-aliases/StandardLoadOptions.md)
* [SpatialLoadOptions](type-aliases/SpatialLoadOptions.md)
* [SpatialLoadFileOptions](type-aliases/SpatialLoadFileOptions.md)
* [StandardLoadFileOptions](type-aliases/StandardLoadFileOptions.md)
* [LoadFileOptions](type-aliases/LoadFileOptions.md)
## Variables
* [MAIN\_VIEW](variables/MAIN_VIEW.md)
* [LayoutTypes](variables/LayoutTypes.md)
* [~~DEFAULT\_MOSAIC\_LAYOUT~~](variables/DEFAULT_MOSAIC_LAYOUT.md)
* [MosaicLayoutDirection](variables/MosaicLayoutDirection.md)
* [MosaicLayoutParent](variables/MosaicLayoutParent.md)
* [MosaicLayoutNodeKey](variables/MosaicLayoutNodeKey.md)
* [MosaicLayoutNode](variables/MosaicLayoutNode.md)
* [MosaicLayoutConfig](variables/MosaicLayoutConfig.md)
* [LayoutConfig](variables/LayoutConfig.md)
* [DEFAULT\_ROOM\_TITLE](variables/DEFAULT_ROOM_TITLE.md)
* [BaseRoomConfig](variables/BaseRoomConfig.md)
* [DataSourceTypes](variables/DataSourceTypes.md)
* [BaseDataSource](variables/BaseDataSource.md)
* [FileDataSource](variables/FileDataSource.md)
* [UrlDataSource](variables/UrlDataSource.md)
* [SqlQueryDataSource](variables/SqlQueryDataSource.md)
* [DataSource](variables/DataSource.md)
* [LoadFile](variables/LoadFile.md)
* [StandardLoadOptions](variables/StandardLoadOptions.md)
* [SpatialLoadOptions](variables/SpatialLoadOptions.md)
* [SpatialLoadFileOptions](variables/SpatialLoadFileOptions.md)
* [StandardLoadFileOptions](variables/StandardLoadFileOptions.md)
* [LoadFileOptions](variables/LoadFileOptions.md)
## Functions
* [createDefaultMosaicLayout](functions/createDefaultMosaicLayout.md)
* [isMosaicLayoutParent](functions/isMosaicLayoutParent.md)
* [createDefaultBaseRoomConfig](functions/createDefaultBaseRoomConfig.md)
* [isSpatialLoadFileOptions](functions/isSpatialLoadFileOptions.md)
---
---
url: /api/room-shell.md
---
# @sqlrooms/room-shell
A powerful framework for building and managing data rooms in SQLRooms. This package provides components and utilities for creating, configuring, and managing data rooms with an intuitive user interface.
## Features
* 🏗️ **Room Structure**: Tools for defining and managing room structure
* 📊 **Data Sources**: Components for connecting to and managing data sources
* 🧩 **Panel System**: Flexible panel-based UI for room components
* 🔄 **State Management**: Robust state management using Zustand
* 📁 **File Handling**: Utilities for processing and managing room files
* 🧰 **Extensible Architecture**: Easily extend with custom components and panels
## Installation
```bash
npm install @sqlrooms/room-shell
# or
yarn add @sqlrooms/room-shell
```
## Basic Usage
### Creating a Room Builder
```tsx
import {RoomShell} from '@sqlrooms/room-shell';
function MyApp() {
return (
);
}
```
### Working with Room State
The room-shell package uses Zustand for state management. You can create a custom store with room-specific state and actions.
```tsx
import {
createRoomShellSlice,
createRoomStore,
RoomState,
BaseRoomConfig,
} from '@sqlrooms/room-shell';
import {z} from 'zod';
// Define your custom config schema (optional)
const MyRoomConfig = BaseRoomConfig.extend({
myCustomSetting: z.string().default('default value'),
});
type MyRoomConfig = z.infer;
// Define your custom app state
type MyRoomState = RoomState & {
myFeatureData: any[];
addItem: (item: any) => void;
removeItem: (id: string) => void;
};
// Create a room store with custom state
export const {roomStore, useRoomStore} = createRoomStore<
MyRoomConfig,
MyRoomState
>((set, get, store) => ({
// Base room slice with initial configuration
...createRoomShellSlice({
config: {
title: 'My Room',
layout: {
/* layout configuration */
},
dataSources: [],
myCustomSetting: 'custom value',
},
room: {
panels: {
/* panel definitions */
},
},
})(set, get, store),
// Custom state and actions
myFeatureData: [],
addItem: (item) =>
set((state) => ({
myFeatureData: [...state.myFeatureData, item],
})),
removeItem: (id) =>
set((state) => ({
myFeatureData: state.myFeatureData.filter((item) => item.id !== id),
})),
}));
// Use the store in a component with selector for better performance
function MyComponent() {
// Use selectors for better performance
const myFeatureData = useRoomStore((state) => state.myFeatureData);
const addItem = useRoomStore((state) => state.addItem);
return (
My Items ({myFeatureData.length})
{/* Render items */}
);
}
```
### Persisting Room Configuration
The room configuration is designed to be persisted between sessions. You can use Zustand's persist middleware to save the configuration to localStorage or any other storage:
```tsx
import {persist} from 'zustand/middleware';
import {
createRoomShellSlice,
createRoomStore,
RoomState,
BaseRoomConfig,
} from '@sqlrooms/room-shell';
import {z} from 'zod';
// Define your custom config schema
const MyRoomConfig = BaseRoomConfig.extend({
myCustomSetting: z.string().default('default value'),
});
type MyRoomConfig = z.infer;
// Define your custom app state
type MyRoomState = RoomState & {
myFeatureData: any[];
addItem: (item: any) => void;
};
// Create a store with persistence
export const {roomStore, useRoomStore} = createRoomStore<
MyRoomConfig,
MyRoomState
>(
persist(
(set, get, store) => ({
// Base room slice
...createRoomShellSlice({
config: {
title: 'My Room',
layout: {
/* layout configuration */
},
dataSources: [],
myCustomSetting: 'custom value',
},
room: {
panels: {
/* panel definitions */
},
},
})(set, get, store),
// Custom state and actions
myFeatureData: [],
addItem: (item) =>
set((state) => ({
myFeatureData: [...state.myFeatureData, item],
})),
}),
{
name: 'my-room-storage',
partialize: (state) => ({
// Persist only the config part of the state
config: state.config,
}),
},
),
);
```
### Integrating Multiple Feature Slices
For larger applications, you can organize your state into feature slices:
```tsx
import {
createRoomShellSlice,
createRoomStore,
RoomState,
} from '@sqlrooms/room-shell';
import {createMyFeatureSlice, MyFeatureState} from './myFeatureSlice';
import {
createAnotherFeatureSlice,
AnotherFeatureState,
} from './anotherFeatureSlice';
// Combined app state type
type RoomState = RoomState & MyFeatureState & AnotherFeatureState;
// Create a store with multiple slices
export const {roomStore, useRoomStore} = createRoomStore<
MyRoomConfig,
RoomState
>((set, get, store) => ({
// Base room slice
...createRoomShellSlice({
config: {
/* initial config */
},
room: {
panels: {
/* panel definitions */
},
},
})(set, get, store),
// Feature slices
...createMyFeatureSlice()(set, get, store),
...createAnotherFeatureSlice({
// Feature-specific options
customOption: 'value',
})(set, get, store),
}));
```
### Managing Data Sources
```tsx
import {
FileDataSourcesPanel,
TablesListPanel,
DataSourceType,
} from '@sqlrooms/room-shell';
function DataSourcesSection() {
// Use selectors for better performance
const addDataSource = useRoomStore((state) => state.room.addDataSource);
const addRoomFile = useRoomStore((state) => state.room.addRoomFile);
const handleFileDrop = async (files) => {
for (const file of files) {
await addRoomFile(file);
}
};
const handleAddCsvUrl = (url) => {
addDataSource({
type: DataSourceType.url,
url,
tableName: 'data_from_url',
});
};
const handleAddSqlQuery = (query) => {
addDataSource({
type: DataSourceType.sqlQuery,
query,
tableName: 'query_results',
});
};
return (
);
}
```
### Creating Custom Panels
```tsx
import {RoomPanel, RoomPanelHeader} from '@sqlrooms/room-shell';
function CustomPanel({title, children}) {
return (
{children}
);
}
```
## RoomStore API Reference
The RoomStore is the core of the room-shell package. It provides a comprehensive set of properties and methods for managing room state.
### State Properties
#### `config`
The room configuration, which can be persisted between sessions.
```tsx
const config = useRoomStore((state) => state.config);
console.log(config.title); // Access room title
```
#### `schema`
The database schema name used for the room.
```tsx
const schema = useRoomStore((state) => state.room.schema);
```
#### `tasksProgress`
A record of task progress information, useful for displaying loading indicators.
```tsx
const tasksProgress = useRoomStore((state) => state.room.tasksProgress);
// Example: { "init-db": { message: "Initializing database...", progress: 0.5 } }
```
#### `roomId`
The unique identifier for the room, undefined for new rooms.
```tsx
const roomId = useRoomStore((state) => state.room.roomId);
```
#### `panels`
A record of panel information, including title, icon, component, and placement.
```tsx
const panels = useRoomStore((state) => state.room.panels);
// Example: { "data-sources": { title: "Data Sources", icon: DatabaseIcon, ... } }
```
#### `isReadOnly`
Whether the room is in read-only mode.
```tsx
const isReadOnly = useRoomStore((state) => state.room.isReadOnly);
```
#### `tables`
An array of data tables available in the room.
```tsx
const tables = useRoomStore((state) => state.room.tables);
// Access table schemas and metadata
```
#### `roomFiles`
An array of room file information.
```tsx
const roomFiles = useRoomStore((state) => state.room.roomFiles);
```
#### `roomFilesProgress`
A record of file processing progress information.
```tsx
const roomFilesProgress = useRoomStore((state) => state.room.roomFilesProgress);
```
#### `lastSavedConfig`
The last saved room configuration, used to check for unsaved changes.
```tsx
const lastSavedConfig = useRoomStore((state) => state.room.lastSavedConfig);
```
#### `initialized`
Whether the room has been initialized.
```tsx
const initialized = useRoomStore((state) => state.room.initialized);
```
#### `isDataAvailable`
Whether the room data has been loaded.
```tsx
const isDataAvailable = useRoomStore((state) => state.room.isDataAvailable);
```
#### `dataSourceStates`
A record of data source states by table name.
```tsx
const dataSourceStates = useRoomStore((state) => state.room.dataSourceStates);
```
#### `tableRowCounts`
A record of row counts by table name.
```tsx
const tableRowCounts = useRoomStore((state) => state.room.tableRowCounts);
```
### Methods
#### `initialize()`
Initialize the room state.
```tsx
const initialize = useRoomStore((state) => state.room.initialize);
await initialize();
```
#### `setTaskProgress(id, taskProgress)`
Set the progress of a task.
```tsx
const setTaskProgress = useRoomStore((state) => state.room.setTaskProgress);
setTaskProgress('my-task', {message: 'Processing...', progress: 0.5});
```
#### `getLoadingProgress()`
Get the current loading progress.
```tsx
const getLoadingProgress = useRoomStore(
(state) => state.room.getLoadingProgress,
);
const progress = getLoadingProgress();
```
#### `setRoomConfig(config)`
Set the room configuration.
```tsx
const setRoomConfig = useRoomStore((state) => state.room.setRoomConfig);
const config = useRoomStore((state) => state.config);
setRoomConfig({...config, title: 'New Title'});
```
#### `setLastSavedConfig(config)`
Set the last saved room configuration.
```tsx
const setLastSavedConfig = useRoomStore(
(state) => state.room.setLastSavedConfig,
);
const config = useRoomStore((state) => state.config);
setLastSavedConfig(config);
```
#### `hasUnsavedChanges()`
Check if the room has unsaved changes.
```tsx
const hasUnsavedChanges = useRoomStore((state) => state.room.hasUnsavedChanges);
if (hasUnsavedChanges()) {
// Prompt user to save changes
}
```
#### `setLayout(layout)`
Set the room layout configuration.
```tsx
const setLayout = useRoomStore((state) => state.room.setLayout);
setLayout(newLayout);
```
#### `togglePanel(panel, show)`
Toggle the visibility of a panel.
```tsx
const togglePanel = useRoomStore((state) => state.room.togglePanel);
togglePanel('data-sources', true); // Show the data sources panel
```
#### `togglePanelPin(panel)`
Toggle the pin state of a panel.
```tsx
const togglePanelPin = useRoomStore((state) => state.room.togglePanelPin);
togglePanelPin('data-sources');
```
#### `addOrUpdateSqlQueryDataSource(tableName, query, oldTableName)`
Add or update a SQL query data source.
```tsx
const addOrUpdateSqlQueryDataSource = useRoomStore(
(state) => state.room.addOrUpdateSqlQueryDataSource,
);
await addOrUpdateSqlQueryDataSource(
'filtered_data',
'SELECT * FROM data WHERE value > 10',
);
```
#### `removeSqlQueryDataSource(tableName)`
Remove a SQL query data source.
```tsx
const removeSqlQueryDataSource = useRoomStore(
(state) => state.room.removeSqlQueryDataSource,
);
await removeSqlQueryDataSource('filtered_data');
```
#### `addRoomFile(info, desiredTableName)`
Add a room file.
```tsx
const addRoomFile = useRoomStore((state) => state.room.addRoomFile);
const dataTable = await addRoomFile(file, 'my_data');
```
#### `removeRoomFile(pathname)`
Remove a room file.
```tsx
const removeRoomFile = useRoomStore((state) => state.room.removeRoomFile);
removeRoomFile('/path/to/file.csv');
```
#### `maybeDownloadDataSources()`
Download data sources if needed.
```tsx
const maybeDownloadDataSources = useRoomStore(
(state) => state.room.maybeDownloadDataSources,
);
await maybeDownloadDataSources();
```
#### `setRoomFiles(info)`
Set the room files.
```tsx
const setRoomFiles = useRoomStore((state) => state.room.setRoomFiles);
setRoomFiles(fileInfoArray);
```
#### `setRoomFileProgress(pathname, fileState)`
Set the progress of a room file.
```tsx
const setRoomFileProgress = useRoomStore(
(state) => state.room.setRoomFileProgress,
);
setRoomFileProgress('/path/to/file.csv', {status: 'processing'});
```
#### `addTable(tableName, data)`
Add a table to the room.
```tsx
const addTable = useRoomStore((state) => state.db.addTable);
await addTable('my_table', records);
```
#### `addDataSource(dataSource, status)`
Add a data source to the room.
```tsx
const addDataSource = useRoomStore((state) => state.room.addDataSource);
await addDataSource({
type: 'url',
url: 'https://example.com/data.csv',
tableName: 'external_data',
});
```
#### `getTable(tableName)`
Get a table by name.
```tsx
const getTable = useRoomStore((state) => state.room.getTable);
const table = getTable('my_table');
```
#### `setTables(dataTable)`
Set the room tables.
```tsx
const setTables = useRoomStore((state) => state.room.setTables);
await setTables(tableArray);
```
#### `setTableRowCount(tableName, rowCount)`
Set the row count for a table.
```tsx
const setTableRowCount = useRoomStore((state) => state.room.setTableRowCount);
setTableRowCount('my_table', 1000);
```
#### `setRoomTitle(title)`
Set the room title.
```tsx
const setRoomTitle = useRoomStore((state) => state.room.setRoomTitle);
setRoomTitle('My Awesome Room');
```
#### `setDescription(description)`
Set the room description.
```tsx
const setDescription = useRoomStore((state) => state.room.setDescription);
setDescription('This is a description of my room');
```
#### `areDatasetsReady()`
Check if all datasets are ready.
```tsx
const areDatasetsReady = useRoomStore((state) => state.room.areDatasetsReady);
if (areDatasetsReady()) {
// Proceed with data operations
}
```
#### `findTableByName(tableName)`
Find a table by name.
```tsx
const findTableByName = useRoomStore((state) => state.room.findTableByName);
const table = findTableByName('my_table');
```
#### `updateReadyDataSources()`
Update the status of all data sources based on the current tables.
```tsx
const updateReadyDataSources = useRoomStore(
(state) => state.room.updateReadyDataSources,
);
await updateReadyDataSources();
```
#### `onDataUpdated()`
Called when data has been updated.
```tsx
const onDataUpdated = useRoomStore((state) => state.room.onDataUpdated);
await onDataUpdated();
```
#### `areViewsReadyToRender()`
Check if views are ready to render.
```tsx
const areViewsReadyToRender = useRoomStore(
(state) => state.room.areViewsReadyToRender,
);
if (areViewsReadyToRender()) {
// Render views
}
```
#### `refreshTableSchemas()`
Refresh table schemas from the database.
```tsx
const refreshTableSchemas = useRoomStore(
(state) => state.room.refreshTableSchemas,
);
const updatedTables = await refreshTableSchemas();
```
## Advanced Features
* **Custom State Slices**: Extend the room state with custom slices
* **Task Management**: Built-in task progress tracking
* **Panel Configuration**: Configure and arrange panels dynamically
* **Data Source Integration**: Connect to various data sources
* **File Processing**: Process and transform data files
For more information, visit the SQLRooms documentation.
```
```
## Enumerations
* [DataSourceStatus](enumerations/DataSourceStatus.md)
## Interfaces
* [StoreApi](interfaces/StoreApi.md)
* [RoomSlice](interfaces/RoomSlice.md)
## Type Aliases
* [StateCreator](type-aliases/StateCreator.md)
* [LayoutTypes](type-aliases/LayoutTypes.md)
* [MosaicLayoutDirection](type-aliases/MosaicLayoutDirection.md)
* [MosaicLayoutParent](type-aliases/MosaicLayoutParent.md)
* [MosaicLayoutNodeKey](type-aliases/MosaicLayoutNodeKey.md)
* [MosaicLayoutNode](type-aliases/MosaicLayoutNode.md)
* [MosaicLayoutConfig](type-aliases/MosaicLayoutConfig.md)
* [LayoutConfig](type-aliases/LayoutConfig.md)
* [RoomPanelInfo](type-aliases/RoomPanelInfo.md)
* [BaseRoomConfig](type-aliases/BaseRoomConfig.md)
* [DataSourceTypes](type-aliases/DataSourceTypes.md)
* [BaseDataSource](type-aliases/BaseDataSource.md)
* [FileDataSource](type-aliases/FileDataSource.md)
* [UrlDataSource](type-aliases/UrlDataSource.md)
* [SqlQueryDataSource](type-aliases/SqlQueryDataSource.md)
* [DataSource](type-aliases/DataSource.md)
* [LoadFile](type-aliases/LoadFile.md)
* [StandardLoadOptions](type-aliases/StandardLoadOptions.md)
* [SpatialLoadOptions](type-aliases/SpatialLoadOptions.md)
* [SpatialLoadFileOptions](type-aliases/SpatialLoadFileOptions.md)
* [StandardLoadFileOptions](type-aliases/StandardLoadFileOptions.md)
* [LoadFileOptions](type-aliases/LoadFileOptions.md)
* [RoomShellSliceState](type-aliases/RoomShellSliceState.md)
* [RoomFileState](type-aliases/RoomFileState.md)
* [RoomFileInfo](type-aliases/RoomFileInfo.md)
* [DataSourceState](type-aliases/DataSourceState.md)
* [RoomStateProviderProps](type-aliases/RoomStateProviderProps.md)
* [RoomStore](type-aliases/RoomStore.md)
* [RoomStateProps](type-aliases/RoomStateProps.md)
* [TaskProgress](type-aliases/TaskProgress.md)
* [RoomStateActions](type-aliases/RoomStateActions.md)
* [RoomState](type-aliases/RoomState.md)
## Variables
* [MAIN\_VIEW](variables/MAIN_VIEW.md)
* [LayoutTypes](variables/LayoutTypes.md)
* [~~DEFAULT\_MOSAIC\_LAYOUT~~](variables/DEFAULT_MOSAIC_LAYOUT.md)
* [MosaicLayoutDirection](variables/MosaicLayoutDirection.md)
* [MosaicLayoutParent](variables/MosaicLayoutParent.md)
* [MosaicLayoutNodeKey](variables/MosaicLayoutNodeKey.md)
* [MosaicLayoutNode](variables/MosaicLayoutNode.md)
* [MosaicLayoutConfig](variables/MosaicLayoutConfig.md)
* [LayoutConfig](variables/LayoutConfig.md)
* [DEFAULT\_ROOM\_TITLE](variables/DEFAULT_ROOM_TITLE.md)
* [BaseRoomConfig](variables/BaseRoomConfig.md)
* [DataSourceTypes](variables/DataSourceTypes.md)
* [BaseDataSource](variables/BaseDataSource.md)
* [FileDataSource](variables/FileDataSource.md)
* [UrlDataSource](variables/UrlDataSource.md)
* [SqlQueryDataSource](variables/SqlQueryDataSource.md)
* [DataSource](variables/DataSource.md)
* [LoadFile](variables/LoadFile.md)
* [StandardLoadOptions](variables/StandardLoadOptions.md)
* [SpatialLoadOptions](variables/SpatialLoadOptions.md)
* [SpatialLoadFileOptions](variables/SpatialLoadFileOptions.md)
* [StandardLoadFileOptions](variables/StandardLoadFileOptions.md)
* [LoadFileOptions](variables/LoadFileOptions.md)
## Functions
* [createDefaultMosaicLayout](functions/createDefaultMosaicLayout.md)
* [isMosaicLayoutParent](functions/isMosaicLayoutParent.md)
* [createDefaultBaseRoomConfig](functions/createDefaultBaseRoomConfig.md)
* [isSpatialLoadFileOptions](functions/isSpatialLoadFileOptions.md)
* [RoomShell](functions/RoomShell.md)
* [SidebarButton](functions/SidebarButton.md)
* [RoomShellSidebarButton](functions/RoomShellSidebarButton.md)
* [RoomShellSidebarButtons](functions/RoomShellSidebarButtons.md)
* [createRoomShellSlice](functions/createRoomShellSlice.md)
* [useBaseRoomShellStore](functions/useBaseRoomShellStore.md)
* [createSlice](functions/createSlice.md)
* [FileDataSourceCard](functions/FileDataSourceCard.md)
* [FileDataSourcesPanel](functions/FileDataSourcesPanel.md)
* [TableCard](functions/TableCard.md)
* [TablesListPanel](functions/TablesListPanel.md)
* [PanelHeaderButton](functions/PanelHeaderButton.md)
* [RoomPanel](functions/RoomPanel.md)
* [RoomPanelHeader](functions/RoomPanelHeader.md)
* [RoomStateContext](functions/RoomStateContext.md)
* [RoomStateProvider](functions/RoomStateProvider.md)
* [useBaseRoomStore](functions/useBaseRoomStore.md)
* [createRoomSlice](functions/createRoomSlice.md)
* [createBaseSlice](functions/createBaseSlice.md)
* [createRoomStore](functions/createRoomStore.md)
* [isRoomSliceWithInitialize](functions/isRoomSliceWithInitialize.md)
* [createRoomStoreCreator](functions/createRoomStoreCreator.md)
---
---
url: /api/room-store.md
---
# @sqlrooms/room-store
This package provides the core state management for SQLRooms using [Zustand](https://github.com/pmndrs/zustand). It is designed to be extensible, allowing you to build custom room experiences by creating and composing state "slices".
## Installation
```bash
npm install @sqlrooms/room-store @sqlrooms/room-config zod zustand
```
## Core Concepts
### RoomStore
The `RoomStore` is a Zustand store that holds the entire state of a room. It is created by calling `createRoomStore` with a function that composes one or more slice creators.
### RoomState
The `RoomState` is the object that defines the shape of the store. It has two main properties:
* `config`: This holds the configuration of the room that is persisted. This is defined by a `zod` schema, often extending the `BaseRoomConfig` from `@sqlrooms/room-config`.
* `room`: This holds the client-side state of the room, such as task progress, and provides actions for interacting with the room.
### Slices
A slice is a piece of the room's state and its associated actions. You can create your own slices to add custom functionality to your room. The framework provides `createRoomShellSlice` to create the base slice with core room functionality. You combine this with your own slices inside the `createRoomStore` composer function.
## Basic Usage
Here's an example of how to create a room store with a custom feature slice.
```typescript
import {
createRoomStore,
createRoomShellSlice,
RoomState,
} from '@sqlrooms/room-store';
import {BaseRoomConfig} from '@sqlrooms/room-config';
import {z} from 'zod';
import {StateCreator} from 'zustand';
// 1. Define your persisted room configuration schema using Zod.
// This extends the base config with a custom property.
export const MyRoomConfig = BaseRoomConfig.extend({
defaultChartType: z.enum(['bar', 'line', 'scatter']).default('bar'),
});
export type MyRoomConfig = z.infer;
// 2. Define the state and actions for your custom feature slice.
export interface MyFeatureSlice {
activeChartId: string | null;
setActiveChartId: (id: string | null) => void;
}
// 3. Create your custom slice.
export const createMyFeatureSlice: StateCreator = (set) => ({
activeChartId: null,
setActiveChartId: (id) => set({activeChartId: id}),
});
// 4. Define the full state of your room, combining the base RoomState
// with your custom slice's state.
export type MyRoomState = RoomState & MyFeatureSlice;
// 5. Create the room store by composing the base slice and your custom slice.
export const {roomStore, useRoomStore} = createRoomStore<
MyRoomConfig,
MyRoomState
>((set, get, store) => ({
...createRoomShellSlice({
config: {
// You can provide initial values for your config here
title: 'My First Room',
defaultChartType: 'line',
// other properties from BaseRoomConfig will have defaults
},
room: {},
})(set, get, store),
// Add your custom slice to the store
...createMyFeatureSlice(set, get, store),
}));
export {roomStore, useRoomStore};
```
## Providing the Store
To make the store available to your React components, you need to use the `RoomStateProvider` component at the root of your application.
```tsx
import {RoomStateProvider} from '@sqlrooms/room-store';
import {roomStore} from './my-room-store';
function App() {
return (
{/* Your room components go here */}
);
}
```
## Accessing the Store in Components
You can use the `useRoomStore` hook returned by `createRoomStore` to access the room's state and actions from any component.
```tsx
import {useRoomStore} from './my-room-store';
function RoomTitle() {
const title = useRoomStore((state) => state.config.title);
const activeChartId = useRoomStore((state) => state.activeChartId);
const setActiveChartId = useRoomStore((state) => state.setActiveChartId);
return (
{title}
Active Chart: {activeChartId || 'None'}
);
}
```
## Interfaces
* [StoreApi](interfaces/StoreApi.md)
* [RoomSlice](interfaces/RoomSlice.md)
## Type Aliases
* [StateCreator](type-aliases/StateCreator.md)
* [LayoutTypes](type-aliases/LayoutTypes.md)
* [MosaicLayoutDirection](type-aliases/MosaicLayoutDirection.md)
* [MosaicLayoutParent](type-aliases/MosaicLayoutParent.md)
* [MosaicLayoutNodeKey](type-aliases/MosaicLayoutNodeKey.md)
* [MosaicLayoutNode](type-aliases/MosaicLayoutNode.md)
* [MosaicLayoutConfig](type-aliases/MosaicLayoutConfig.md)
* [LayoutConfig](type-aliases/LayoutConfig.md)
* [BaseRoomConfig](type-aliases/BaseRoomConfig.md)
* [DataSourceTypes](type-aliases/DataSourceTypes.md)
* [BaseDataSource](type-aliases/BaseDataSource.md)
* [FileDataSource](type-aliases/FileDataSource.md)
* [UrlDataSource](type-aliases/UrlDataSource.md)
* [SqlQueryDataSource](type-aliases/SqlQueryDataSource.md)
* [DataSource](type-aliases/DataSource.md)
* [LoadFile](type-aliases/LoadFile.md)
* [StandardLoadOptions](type-aliases/StandardLoadOptions.md)
* [SpatialLoadOptions](type-aliases/SpatialLoadOptions.md)
* [SpatialLoadFileOptions](type-aliases/SpatialLoadFileOptions.md)
* [StandardLoadFileOptions](type-aliases/StandardLoadFileOptions.md)
* [LoadFileOptions](type-aliases/LoadFileOptions.md)
* [RoomStateProviderProps](type-aliases/RoomStateProviderProps.md)
* [RoomStore](type-aliases/RoomStore.md)
* [RoomStateProps](type-aliases/RoomStateProps.md)
* [TaskProgress](type-aliases/TaskProgress.md)
* [RoomStateActions](type-aliases/RoomStateActions.md)
* [RoomState](type-aliases/RoomState.md)
## Variables
* [MAIN\_VIEW](variables/MAIN_VIEW.md)
* [LayoutTypes](variables/LayoutTypes.md)
* [~~DEFAULT\_MOSAIC\_LAYOUT~~](variables/DEFAULT_MOSAIC_LAYOUT.md)
* [MosaicLayoutDirection](variables/MosaicLayoutDirection.md)
* [MosaicLayoutParent](variables/MosaicLayoutParent.md)
* [MosaicLayoutNodeKey](variables/MosaicLayoutNodeKey.md)
* [MosaicLayoutNode](variables/MosaicLayoutNode.md)
* [MosaicLayoutConfig](variables/MosaicLayoutConfig.md)
* [LayoutConfig](variables/LayoutConfig.md)
* [DEFAULT\_ROOM\_TITLE](variables/DEFAULT_ROOM_TITLE.md)
* [BaseRoomConfig](variables/BaseRoomConfig.md)
* [DataSourceTypes](variables/DataSourceTypes.md)
* [BaseDataSource](variables/BaseDataSource.md)
* [FileDataSource](variables/FileDataSource.md)
* [UrlDataSource](variables/UrlDataSource.md)
* [SqlQueryDataSource](variables/SqlQueryDataSource.md)
* [DataSource](variables/DataSource.md)
* [LoadFile](variables/LoadFile.md)
* [StandardLoadOptions](variables/StandardLoadOptions.md)
* [SpatialLoadOptions](variables/SpatialLoadOptions.md)
* [SpatialLoadFileOptions](variables/SpatialLoadFileOptions.md)
* [StandardLoadFileOptions](variables/StandardLoadFileOptions.md)
* [LoadFileOptions](variables/LoadFileOptions.md)
## Functions
* [createDefaultMosaicLayout](functions/createDefaultMosaicLayout.md)
* [isMosaicLayoutParent](functions/isMosaicLayoutParent.md)
* [createDefaultBaseRoomConfig](functions/createDefaultBaseRoomConfig.md)
* [isSpatialLoadFileOptions](functions/isSpatialLoadFileOptions.md)
* [RoomStateContext](functions/RoomStateContext.md)
* [RoomStateProvider](functions/RoomStateProvider.md)
* [useBaseRoomStore](functions/useBaseRoomStore.md)
* [createRoomSlice](functions/createRoomSlice.md)
* [createBaseSlice](functions/createBaseSlice.md)
* [createRoomStore](functions/createRoomStore.md)
* [isRoomSliceWithInitialize](functions/isRoomSliceWithInitialize.md)
* [createRoomStoreCreator](functions/createRoomStoreCreator.md)
---
---
url: /api/s3-browser.md
---
# @sqlrooms/s3-browser
This package is part of the SQLRooms framework.
# S3 Browser
A React component library for browsing and interacting with S3-compatible storage services.

## Features
* Directory navigation with breadcrumbs
* File and directory listing
* Multiple file selection
* File metadata display (size, type, last modified)
* S3 utility functions for listing and deleting files
## Installation
```bash
npm install @sqlrooms/s3-browser
# or
yarn add @sqlrooms/s3-browser
```
## Usage
### S3FileBrowser Component
The `S3FileBrowser` component provides a familiar file explorer interface for navigating and selecting files from an S3-like storage.
```tsx
import {S3FileBrowser} from '@sqlrooms/s3-browser';
import {useState} from 'react';
function MyS3Browser() {
const [selectedFiles, setSelectedFiles] = useState([]);
const [selectedDirectory, setSelectedDirectory] = useState('');
return (
console.log('Can confirm:', canConfirm)
}
onChangeSelectedDirectory={setSelectedDirectory}
onChangeSelectedFiles={setSelectedFiles}
/>
);
}
```
### S3 Utility Functions
The package also provides utility functions for working with S3:
```tsx
import {S3Client} from '@aws-sdk/client-s3';
import {
listFilesAndDirectoriesWithPrefix,
deleteS3Files,
} from '@sqlrooms/s3-browser';
// Initialize S3 client
const s3Client = new S3Client({region: 'us-east-1'});
// List files and directories
async function listFiles() {
const files = await listFilesAndDirectoriesWithPrefix(
s3Client,
'my-bucket',
'path/to/directory',
);
console.log(files);
}
// Delete files with a prefix
async function deleteFiles() {
await deleteS3Files(s3Client, 'my-bucket', 'path/to/delete');
}
```
## API Reference
### S3FileBrowser
```tsx
interface S3FileBrowserProps {
/**
* Array of files and directories to display
*/
files?: S3FileOrDirectory[];
/**
* Array of currently selected file keys
*/
selectedFiles: string[];
/**
* Current directory path (empty string for root)
*/
selectedDirectory: string;
/**
* Callback fired when selection state changes
*/
onCanConfirmChange: (canConfirm: boolean) => void;
/**
* Callback fired when directory navigation occurs
*/
onChangeSelectedDirectory: (directory: string) => void;
/**
* Callback fired when file selection changes
*/
onChangeSelectedFiles: (files: string[]) => void;
}
```
### S3FileOrDirectory
```tsx
type S3FileOrDirectory =
| {
key: string;
isDirectory: true;
}
| {
key: string;
isDirectory: false;
lastModified?: Date;
size?: number;
contentType?: string;
};
```
### Utility Functions
```tsx
/**
* Lists files and directories with a given prefix
*/
function listFilesAndDirectoriesWithPrefix(
S3: S3Client,
bucket: string,
prefix?: string,
): Promise;
/**
* Delete all files with the given prefix
*/
function deleteS3Files(
S3: S3Client,
bucket: string,
prefix: string,
): Promise;
```
## Dependencies
* @aws-sdk/client-s3
* React
* @sqlrooms/ui (for UI components)
* @sqlrooms/utils (for formatting utilities)
* zod (for type validation)
## Type Aliases
* [S3FileOrDirectory](type-aliases/S3FileOrDirectory.md)
## Variables
* [S3FileOrDirectory](variables/S3FileOrDirectory.md)
## Functions
* [S3FileBrowser](functions/S3FileBrowser.md)
* [listFilesAndDirectoriesWithPrefix](functions/listFilesAndDirectoriesWithPrefix.md)
* [deleteS3Files](functions/deleteS3Files.md)
---
---
url: /api/schema-tree.md
---
# @sqlrooms/schema-tree
This package is part of the SQLRooms framework.
# DuckDB schema tree
A React component library for rendering DuckDB schema trees in a hierarchical view. It provides components to display database schemas, tables, and columns in an interactive tree structure with features like:
* Expandable/collapsible tree nodes
* Column type badges
* Context menus for actions (e.g. copying column names)
* Customizable node rendering
* Hover states and visual feedback
The main components are:
* `TableSchemaTree`: The root tree component that renders the full schema hierarchy
* `ColumnTreeNode`: Specialized node for displaying column information
* `TreeNodeActionsMenu`: Reusable menu component for node actions
This package is used by SQLRooms to provide schema browsing capabilities in the database explorer interface.
## Functions
* [defaultRenderTableSchemaNode](functions/defaultRenderTableSchemaNode.md)
* [TableSchemaTree](functions/TableSchemaTree.md)
* [BaseTreeNode](functions/BaseTreeNode.md)
* [ColumnTreeNode](functions/ColumnTreeNode.md)
* [DatabaseTreeNode](functions/DatabaseTreeNode.md)
* [SchemaTreeNode](functions/SchemaTreeNode.md)
* [defaultRenderTableNodeMenuItems](functions/defaultRenderTableNodeMenuItems.md)
* [TableTreeNode](functions/TableTreeNode.md)
* [TreeNodeActionsMenu](functions/TreeNodeActionsMenu.md)
* [TreeNodeActionsMenuItem](functions/TreeNodeActionsMenuItem.md)
---
---
url: /api/sql-editor.md
---
# @sqlrooms/sql-editor
This package is part of the SQLRooms framework.
# SQL Editor
A powerful SQL editor component for SQLRooms applications. This package provides React components and hooks for creating interactive SQL query interfaces with Monaco editor integration, table management, and results visualization.
## Features
* 🔍 **Advanced SQL Editing**: Monaco-based SQL editor with syntax highlighting and auto-completion
* 📊 **Data Visualization**: View query results in interactive data tables
* 📑 **Multiple Tabs**: Support for multiple query tabs with save/rename/delete functionality
* 🔄 **State Management**: Zustand-based state management for SQL editor state
* 📦 **Table Management**: Browser for tables in the database with schema information
* 📤 **Data Export**: Export query results to CSV files
* 📝 **Documentation**: Optional documentation panel for SQL reference
## Installation
```bash
npm install @sqlrooms/sql-editor
```
## Basic Usage
### SqlEditor and SqlEditorModal Components
These components must be used within a `RoomShell` which provides the room store context as they rely on the SQLRooms store:
```tsx
import {RoomShell} from '@sqlrooms/room-shell';
import {SqlEditorModal} from '@sqlrooms/sql-editor';
import {useDisclosure} from '@sqlrooms/ui';
import {TerminalIcon} from 'lucide-react';
import {roomStore} from './store';
function MyApp() {
const sqlEditorDisclosure = useDisclosure();
return (
);
}
```
### Store Setup for SQL Editor
The SQL Editor requires a properly configured store with the SQL Editor slice:
```tsx
import {
createRoomShellSlice,
createRoomStore,
RoomState,
} from '@sqlrooms/room-shell';
import {BaseRoomConfig} from '@sqlrooms/room-config';
import {
createDefaultSqlEditorConfig,
createSqlEditorSlice,
SqlEditorSliceConfig,
SqlEditorSliceState,
} from '@sqlrooms/sql-editor';
import {z} from 'zod';
// Define combined config schema
export const RoomConfig = BaseRoomConfig.merge(SqlEditorSliceConfig);
export type RoomConfig = z.infer;
// Define combined state type
export type RoomState = RoomState & SqlEditorSliceState;
// Create combined store
export const {roomStore, useRoomStore} = createRoomStore(
(set, get, store) => ({
// Base room slice
...createRoomShellSlice({
config: {
title: 'SQL Workspace',
// ... other room config
...createDefaultSqlEditorConfig(),
},
})(set, get, store),
// Sql editor slice
...createSqlEditorSlice()(set, get, store),
}),
);
```
### Standalone SqlMonacoEditor Component
Unlike the full SQL Editor components, the `SqlMonacoEditor` can be used as a standalone component without requiring the store:
```tsx
import {SqlMonacoEditor} from '@sqlrooms/sql-editor';
import {useState} from 'react';
function SimpleSqlEditor() {
const [query, setQuery] = useState('SELECT * FROM products');
const handleExecute = () => {
// Execute the query using your own logic
console.log('Executing query:', query);
};
return (
<>
>
);
}
```
### With Custom Documentation Panel
Adding a custom documentation panel to the SQL Editor:
```tsx
import {SqlEditorModal} from '@sqlrooms/sql-editor';
import {useDisclosure} from '@sqlrooms/ui';
import {RoomShell} from '@sqlrooms/room-shell';
import {roomStore} from './store';
function AdvancedSqlEditor() {
const {isOpen, onOpen, onClose} = useDisclosure();
// Custom documentation component
const Documentation = () => (
SQL Reference
SELECT
Retrieves data from a table
SELECT column1, column2 FROM table_name;
{/* More documentation items */}
);
return (
}
/>
);
}
```
## State Management
The SQL editor provides a Zustand slice for managing state. Here's how to set it up:
### Using in a Combined SQLRooms Store
This approach is recommended when integrating multiple SQLRooms components:
```tsx
import {
createSqlEditorSlice,
createDefaultSqlEditorConfig,
SqlEditorSliceState,
SqlEditorSliceConfig,
} from '@sqlrooms/sql-editor';
import {
createRoomShellSlice,
createRoomStore,
RoomState,
RoomShell,
} from '@sqlrooms/room-shell';
import {BaseRoomConfig} from '@sqlrooms/room-config';
import {z} from 'zod';
// 1. Define combined config schema
export const RoomConfig = BaseRoomConfig.merge(SqlEditorSliceConfig);
export type RoomConfig = z.infer;
// 2. Define combined state type
export type RoomState = RoomState & SqlEditorSliceState;
// 3. Create combined store
export const {roomStore, useRoomStore} = createRoomStore(
(set, get, store) => ({
// Base room slice
...createRoomShellSlice({
config: {
title: 'SQL Workspace',
// ... other room config
...createDefaultSqlEditorConfig(),
},
})(set, get, store),
// Sql editor slice
...createSqlEditorSlice()(set, get, store),
}),
);
// 4. Use the store in components
function MyComponent() {
// Access SQL editor state and actions
const runQuery = useRoomStore((state) => state.sqlEditor.runQuery);
const createQueryTab = useRoomStore(
(state) => state.sqlEditor.createQueryTab,
);
// Use actions
const handleExecute = () => {
runQuery('SELECT * FROM users LIMIT 10');
};
return (
{}} />
);
}
```
### Available State Actions
* `sqlEditor.runQuery(query: string)`: Execute a SQL query
* `sqlEditor.createQueryTab(initialQuery?: string)`: Create a new query tab
* `sqlEditor.deleteQueryTab(queryId: string)`: Delete a query tab
* `sqlEditor.renameQueryTab(queryId: string, newName: string)`: Rename a query tab
* `sqlEditor.updateQueryText(queryId: string, queryText: string)`: Update query text
* `sqlEditor.setSelectedQueryId(queryId: string)`: Set the selected query tab
* `sqlEditor.getCurrentQuery(defaultQuery?: string)`: Get current query text
## Available Components
### SqlEditor
The main component providing a full-featured SQL editor interface. Must be used within a RoomShell.
```tsx
import {SqlEditor} from '@sqlrooms/sql-editor';
import {RoomShell} from '@sqlrooms/room-shell';
import {roomStore} from './store';
void}
schema="main"
documentationPanel={ReactNode}
/>
```
### SqlMonacoEditor
A standalone SQL-specific Monaco editor component. Can be used independently without RoomShell.
```tsx
import {SqlMonacoEditor} from '@sqlrooms/sql-editor';
import {useState} from 'react';
function SimpleSqlEditor() {
const [query, setQuery] = useState('SELECT * FROM products');
const handleExecute = () => {
// Execute the query using your own logic
console.log('Executing query:', query);
};
return (
<>
>
);
}
```
### SqlEditorModal
A modal wrapper around the SQL editor. Must be used within a RoomShell.
```tsx
import {SqlEditorModal} from '@sqlrooms/sql-editor';
import {useDisclosure} from '@sqlrooms/ui';
import {RoomShell} from '@sqlrooms/room-shell';
import {roomStore} from './store';
function EditorWithModal() {
const {isOpen, onOpen, onClose} = useDisclosure();
return (
);
}
```
### CreateTableModal
A modal for creating new tables from SQL queries. Must be used within a RoomShell.
```tsx
import {CreateTableModal} from '@sqlrooms/sql-editor';
import {useDisclosure} from '@sqlrooms/ui';
import {RoomShell} from '@sqlrooms/room-shell';
import {roomStore} from './store';
import {useRoomStore} from './store';
function TableCreator() {
const {isOpen, onOpen, onClose} = useDisclosure();
const addOrUpdateSqlQueryDataSource = useRoomStore(
(state) => state.room.addOrUpdateSqlQueryDataSource,
);
return (
);
}
```
### SqlQueryDataSourcesPanel
A panel showing available data sources for SQL queries. Must be used within a RoomShell.
```tsx
import {SqlQueryDataSourcesPanel} from '@sqlrooms/sql-editor';
import {RoomShell} from '@sqlrooms/room-shell';
import {roomStore} from './store';
{
console.log(`Selected table: ${tableName}`);
}}
/>
;
```
## Props
### SqlEditor Props
| Prop | Type | Default | Description |
| ------------------ | --------- | --------- | ------------------------------------- |
| isOpen | boolean | - | Whether the editor is open |
| onClose | function | - | Callback when the editor is closed |
| schema | string | 'main' | Default schema to use for queries |
| documentationPanel | ReactNode | undefined | Custom documentation panel to display |
### SqlMonacoEditor Props
| Prop | Type | Default | Description |
| ---------------- | ----------- | ------- | --------------------------------------- |
| value | string | '' | The SQL query text |
| onChange | function | - | Callback when the query text changes |
| height | string | '300px' | Height of the editor |
| readOnly | boolean | false | Whether the editor is read-only |
| theme | string | 'dark' | Editor theme ('dark' or 'light') |
| tableSchemas | DataTable\[] | \[] | Table schemas for autocompletion |
| customKeywords | string\[] | \[] | Custom SQL keywords for autocompletion |
| customFunctions | string\[] | \[] | Custom SQL functions for autocompletion |
| getLatestSchemas | function | - | Callback to get latest table schemas |
| className | string | - | Additional CSS class names |
| options | object | - | Monaco editor options |
| onMount | function | - | Callback when editor is mounted |
### SqlEditorModal Props
| Prop | Type | Default | Description |
| ------------------ | --------- | --------- | ------------------------------------- |
| isOpen | boolean | - | Whether the modal is open |
| onClose | function | - | Callback when the modal is closed |
| schema | string | 'main' | Default schema to use for queries |
| documentationPanel | ReactNode | undefined | Custom documentation panel to display |
### CreateTableModal Props
| Prop | Type | Default | Description |
| --------------------- | -------- | ------- | --------------------------------- |
| isOpen | boolean | - | Whether the modal is open |
| onClose | function | - | Callback when the modal is closed |
| onAddOrUpdateSqlQuery | function | - | Callback when a table is created |
| query | string | - | SQL query that generated the data |
## Configuration
The SQL editor can be configured through the Zustand store.
```tsx
const config = createDefaultSqlEditorConfig();
// Customize if needed
config.sqlEditor.queries = [
{id: 'default', name: 'Untitled', query: 'SELECT * FROM users LIMIT 10;'},
];
config.sqlEditor.selectedQueryId = 'default';
// Use in store creation
const {roomStore} = createRoomStore({
...createRoomShellSlice({
config: {
...config,
// other config options
},
}),
...createSqlEditorSlice(),
});
```
For more information, visit the SQLRooms documentation.
## Interfaces
* [SqlMonacoEditorProps](interfaces/SqlMonacoEditorProps.md)
* [QueryEditorPanelProps](interfaces/QueryEditorPanelProps.md)
* [QueryResultPanelProps](interfaces/QueryResultPanelProps.md)
* [TableStructurePanelProps](interfaces/TableStructurePanelProps.md)
## Type Aliases
* [SqlEditorSliceConfig](type-aliases/SqlEditorSliceConfig.md)
* [Props](type-aliases/Props.md)
* [QueryResult](type-aliases/QueryResult.md)
* [SqlEditorSliceState](type-aliases/SqlEditorSliceState.md)
* [CreateTableModalProps](type-aliases/CreateTableModalProps.md)
* [SqlEditorHeaderProps](type-aliases/SqlEditorHeaderProps.md)
## Variables
* [SqlEditorSliceConfig](variables/SqlEditorSliceConfig.md)
## Functions
* [createDefaultSqlEditorConfig](functions/createDefaultSqlEditorConfig.md)
* [SqlEditor](functions/SqlEditor.md)
* [SqlEditorModal](functions/SqlEditorModal.md)
* [createSqlEditorSlice](functions/createSqlEditorSlice.md)
* [SqlMonacoEditor](functions/SqlMonacoEditor.md)
* [CreateTableModal](functions/CreateTableModal.md)
* [QueryEditorPanel](functions/QueryEditorPanel.md)
* [QueryEditorPanelActions](functions/QueryEditorPanelActions.md)
* [QueryEditorPanelEditor](functions/QueryEditorPanelEditor.md)
* [QueryEditorPanelTabsList](functions/QueryEditorPanelTabsList.md)
* [QueryResultPanel](functions/QueryResultPanel.md)
* [SqlEditorHeader](functions/SqlEditorHeader.md)
* [SqlQueryDataSourcesPanel](functions/SqlQueryDataSourcesPanel.md)
* [SqlReferenceButton](functions/SqlReferenceButton.md)
* [SqlReferenceButtonContent](functions/SqlReferenceButtonContent.md)
* [TableStructurePanel](functions/TableStructurePanel.md)
---
---
url: /api/sql-editor-config.md
---
# @sqlrooms/sql-editor-config
A central configuration and type definitions package that maintains base SQL editor configuration schemas and Zod schema definitions for SQLRooms. It provides TypeScript types and interfaces along with essential constants and utilities used for managing SQL editor state.
## Features
* 📝 **SQL Editor Configuration**: Define and manage room SQL editor configuration schemas.
* 🔍 **Type Safety**: Strong TypeScript typing for SQL editor configuration objects.
* ✅ **Validation**: Zod schemas for runtime validation of SQL editor configurations.
## Installation
```bash
npm install @sqlrooms/sql-editor-config
# or
yarn add @sqlrooms/sql-editor-config
```
## Basic Usage
### Working with SQL Editor Configuration
```tsx
import {
SqlEditorSliceConfig,
createDefaultSqlEditorConfig,
} from '@sqlrooms/sql-editor-config';
// Create a new SQL editor configuration
const sqlEditorConfig: SqlEditorSliceConfig = createDefaultSqlEditorConfig();
// This can be part of a bigger room configuration
interface RoomConfig {
// ... other properties
sqlEditor: SqlEditorSliceConfig['sqlEditor'];
}
```
## Advanced Features
* **Schema Extensions**: Extend base schemas for custom room types
* **Configuration Validation**: Validate configurations at runtime
* **Serialization**: Convert configurations to/from JSON for storage
For more information, visit the SQLRooms documentation.
```
```
## Type Aliases
* [SqlEditorSliceConfig](type-aliases/SqlEditorSliceConfig.md)
## Variables
* [SqlEditorSliceConfig](variables/SqlEditorSliceConfig.md)
## Functions
* [createDefaultSqlEditorConfig](functions/createDefaultSqlEditorConfig.md)
---
---
url: /api/ui.md
---
# @sqlrooms/ui
A comprehensive UI component library for SQLRooms applications, built on top of React and Tailwind CSS. This package provides a collection of reusable, accessible, and customizable components designed to create consistent and beautiful user interfaces.
This library is based on [shadcn/ui](https://ui.shadcn.com/), a collection of beautifully designed, accessible components that can be copied and pasted into your apps.
## Features
* 🎨 **Modern Design**: Clean, modern components following design best practices
* ♿ **Accessibility**: Components built with accessibility in mind
* 🌗 **Theming**: Support for light and dark modes
* 📱 **Responsive**: Mobile-friendly components that adapt to different screen sizes
* 🧩 **Composable**: Components designed to work together seamlessly
* 🔄 **React Hooks**: Useful hooks for common UI patterns
## Installation
```bash
npm install @sqlrooms/ui
# or
yarn add @sqlrooms/ui
```
## Basic Usage
### Using Components
```tsx
import {Button, Card, Input} from '@sqlrooms/ui';
function LoginForm() {
return (
);
}
```
## Available Components
* **Layout**: Card, Resizable, Tabs
* **Forms**: Button, Checkbox, Input, Select, Slider, Switch, Textarea
* **Feedback**: Alert, Progress, Spinner, Toast
* **Navigation**: Accordion, Breadcrumb, Dropdown Menu
* **Overlay**: Dialog, Popover, Tooltip
* **Data Display**: Badge, Table
* **Utility**: Error Boundary, Theme Switch
## Advanced Features
* **Component Composition**: Build complex UIs by composing simple components
* **Form Handling**: Integrated with React Hook Form for easy form management
* **Custom Styling**: Extend components with custom styles using Tailwind CSS
* **Animation**: Smooth transitions and animations for interactive elements
For more information, visit the SQLRooms documentation.
## Classes
* [ErrorBoundary](classes/ErrorBoundary.md)
## Interfaces
* [BadgeProps](interfaces/BadgeProps.md)
* [ButtonProps](interfaces/ButtonProps.md)
* [CopyButtonProps](interfaces/CopyButtonProps.md)
* [Dimensions](interfaces/Dimensions.md)
* [UseAspectRatioDimensionsProps](interfaces/UseAspectRatioDimensionsProps.md)
* [UseDisclosureReturnValue](interfaces/UseDisclosureReturnValue.md)
## Type Aliases
* [CalendarProps](type-aliases/CalendarProps.md)
* [ToastProps](type-aliases/ToastProps.md)
* [ToastActionElement](type-aliases/ToastActionElement.md)
* [TreeNodeData](type-aliases/TreeNodeData.md)
## Functions
* [CollapsibleTrigger](functions/CollapsibleTrigger.md)
* [CollapsibleContent](functions/CollapsibleContent.md)
* [Collapsible](functions/Collapsible.md)
* [Slot](functions/Slot.md)
* [Accordion](functions/Accordion.md)
* [AccordionItem](functions/AccordionItem.md)
* [AccordionTrigger](functions/AccordionTrigger.md)
* [AccordionContent](functions/AccordionContent.md)
* [Alert](functions/Alert.md)
* [AlertTitle](functions/AlertTitle.md)
* [AlertDescription](functions/AlertDescription.md)
* [AspectRatio](functions/AspectRatio.md)
* [badgeVariants](functions/badgeVariants.md)
* [Badge](functions/Badge.md)
* [Breadcrumb](functions/Breadcrumb.md)
* [BreadcrumbList](functions/BreadcrumbList.md)
* [BreadcrumbItem](functions/BreadcrumbItem.md)
* [BreadcrumbLink](functions/BreadcrumbLink.md)
* [BreadcrumbPage](functions/BreadcrumbPage.md)
* [BreadcrumbSeparator](functions/BreadcrumbSeparator.md)
* [BreadcrumbEllipsis](functions/BreadcrumbEllipsis.md)
* [buttonVariants](functions/buttonVariants.md)
* [Button](functions/Button.md)
* [Calendar](functions/Calendar.md)
* [Card](functions/Card.md)
* [CardHeader](functions/CardHeader.md)
* [CardTitle](functions/CardTitle.md)
* [CardDescription](functions/CardDescription.md)
* [CardContent](functions/CardContent.md)
* [CardFooter](functions/CardFooter.md)
* [Checkbox](functions/Checkbox.md)
* [ComboboxDemo](functions/ComboboxDemo.md)
* [Command](functions/Command.md)
* [CommandDialog](functions/CommandDialog.md)
* [CommandInput](functions/CommandInput.md)
* [CommandList](functions/CommandList.md)
* [CommandEmpty](functions/CommandEmpty.md)
* [CommandGroup](functions/CommandGroup.md)
* [CommandSeparator](functions/CommandSeparator.md)
* [CommandItem](functions/CommandItem.md)
* [CommandShortcut](functions/CommandShortcut.md)
* [ContextMenu](functions/ContextMenu.md)
* [ContextMenuTrigger](functions/ContextMenuTrigger.md)
* [ContextMenuGroup](functions/ContextMenuGroup.md)
* [ContextMenuPortal](functions/ContextMenuPortal.md)
* [ContextMenuSub](functions/ContextMenuSub.md)
* [ContextMenuRadioGroup](functions/ContextMenuRadioGroup.md)
* [ContextMenuSubTrigger](functions/ContextMenuSubTrigger.md)
* [ContextMenuSubContent](functions/ContextMenuSubContent.md)
* [ContextMenuContent](functions/ContextMenuContent.md)
* [ContextMenuItem](functions/ContextMenuItem.md)
* [ContextMenuCheckboxItem](functions/ContextMenuCheckboxItem.md)
* [ContextMenuRadioItem](functions/ContextMenuRadioItem.md)
* [ContextMenuLabel](functions/ContextMenuLabel.md)
* [ContextMenuSeparator](functions/ContextMenuSeparator.md)
* [ContextMenuShortcut](functions/ContextMenuShortcut.md)
* [CopyButton](functions/CopyButton.md)
* [Dialog](functions/Dialog.md)
* [DialogTrigger](functions/DialogTrigger.md)
* [DialogPortal](functions/DialogPortal.md)
* [DialogClose](functions/DialogClose.md)
* [DialogOverlay](functions/DialogOverlay.md)
* [DialogContent](functions/DialogContent.md)
* [DialogHeader](functions/DialogHeader.md)
* [DialogFooter](functions/DialogFooter.md)
* [DialogTitle](functions/DialogTitle.md)
* [DialogDescription](functions/DialogDescription.md)
* [Drawer](functions/Drawer.md)
* [DrawerTrigger](functions/DrawerTrigger.md)
* [DrawerPortal](functions/DrawerPortal.md)
* [DrawerClose](functions/DrawerClose.md)
* [DrawerHandle](functions/DrawerHandle.md)
* [DrawerOverlay](functions/DrawerOverlay.md)
* [DrawerContent](functions/DrawerContent.md)
* [DrawerHeader](functions/DrawerHeader.md)
* [DrawerFooter](functions/DrawerFooter.md)
* [DrawerTitle](functions/DrawerTitle.md)
* [DrawerDescription](functions/DrawerDescription.md)
* [DropdownMenu](functions/DropdownMenu.md)
* [DropdownMenuTrigger](functions/DropdownMenuTrigger.md)
* [DropdownMenuGroup](functions/DropdownMenuGroup.md)
* [DropdownMenuPortal](functions/DropdownMenuPortal.md)
* [DropdownMenuSub](functions/DropdownMenuSub.md)
* [DropdownMenuRadioGroup](functions/DropdownMenuRadioGroup.md)
* [DropdownMenuSubTrigger](functions/DropdownMenuSubTrigger.md)
* [DropdownMenuSubContent](functions/DropdownMenuSubContent.md)
* [DropdownMenuContent](functions/DropdownMenuContent.md)
* [DropdownMenuItem](functions/DropdownMenuItem.md)
* [DropdownMenuCheckboxItem](functions/DropdownMenuCheckboxItem.md)
* [DropdownMenuRadioItem](functions/DropdownMenuRadioItem.md)
* [DropdownMenuLabel](functions/DropdownMenuLabel.md)
* [DropdownMenuSeparator](functions/DropdownMenuSeparator.md)
* [DropdownMenuShortcut](functions/DropdownMenuShortcut.md)
* [EditableText](functions/EditableText.md)
* [ErrorPane](functions/ErrorPane.md)
* [Form](functions/Form.md)
* [FormField](functions/FormField.md)
* [useFormField](functions/useFormField.md)
* [FormItem](functions/FormItem.md)
* [FormLabel](functions/FormLabel.md)
* [FormControl](functions/FormControl.md)
* [FormDescription](functions/FormDescription.md)
* [FormMessage](functions/FormMessage.md)
* [Input](functions/Input.md)
* [Label](functions/Label.md)
* [MenubarMenu](functions/MenubarMenu.md)
* [MenubarGroup](functions/MenubarGroup.md)
* [MenubarPortal](functions/MenubarPortal.md)
* [MenubarRadioGroup](functions/MenubarRadioGroup.md)
* [MenubarSub](functions/MenubarSub.md)
* [Menubar](functions/Menubar.md)
* [MenubarTrigger](functions/MenubarTrigger.md)
* [MenubarSubTrigger](functions/MenubarSubTrigger.md)
* [MenubarSubContent](functions/MenubarSubContent.md)
* [MenubarContent](functions/MenubarContent.md)
* [MenubarItem](functions/MenubarItem.md)
* [MenubarCheckboxItem](functions/MenubarCheckboxItem.md)
* [MenubarRadioItem](functions/MenubarRadioItem.md)
* [MenubarLabel](functions/MenubarLabel.md)
* [MenubarSeparator](functions/MenubarSeparator.md)
* [MenubarShortcut](functions/MenubarShortcut.md)
* [Pagination](functions/Pagination.md)
* [PaginationContent](functions/PaginationContent.md)
* [PaginationItem](functions/PaginationItem.md)
* [PaginationLink](functions/PaginationLink.md)
* [PaginationPrevious](functions/PaginationPrevious.md)
* [PaginationNext](functions/PaginationNext.md)
* [PaginationEllipsis](functions/PaginationEllipsis.md)
* [Popover](functions/Popover.md)
* [PopoverTrigger](functions/PopoverTrigger.md)
* [PopoverAnchor](functions/PopoverAnchor.md)
* [PopoverContent](functions/PopoverContent.md)
* [ProgressModal](functions/ProgressModal.md)
* [Progress](functions/Progress.md)
* [RadioGroup](functions/RadioGroup.md)
* [RadioGroupItem](functions/RadioGroupItem.md)
* [ResizablePanelGroup](functions/ResizablePanelGroup.md)
* [ResizablePanel](functions/ResizablePanel.md)
* [ResizableHandle](functions/ResizableHandle.md)
* [ScrollArea](functions/ScrollArea.md)
* [ScrollBar](functions/ScrollBar.md)
* [Select](functions/Select.md)
* [SelectGroup](functions/SelectGroup.md)
* [SelectValue](functions/SelectValue.md)
* [SelectTrigger](functions/SelectTrigger.md)
* [SelectScrollUpButton](functions/SelectScrollUpButton.md)
* [SelectScrollDownButton](functions/SelectScrollDownButton.md)
* [SelectContent](functions/SelectContent.md)
* [SelectLabel](functions/SelectLabel.md)
* [SelectItem](functions/SelectItem.md)
* [SelectSeparator](functions/SelectSeparator.md)
* [Separator](functions/Separator.md)
* [Sheet](functions/Sheet.md)
* [SheetTrigger](functions/SheetTrigger.md)
* [SheetClose](functions/SheetClose.md)
* [SheetPortal](functions/SheetPortal.md)
* [SheetOverlay](functions/SheetOverlay.md)
* [SheetContent](functions/SheetContent.md)
* [SheetHeader](functions/SheetHeader.md)
* [SheetFooter](functions/SheetFooter.md)
* [SheetTitle](functions/SheetTitle.md)
* [SheetDescription](functions/SheetDescription.md)
* [SkeletonPane](functions/SkeletonPane.md)
* [Skeleton](functions/Skeleton.md)
* [Slider](functions/Slider.md)
* [SpinnerPane](functions/SpinnerPane.md)
* [Spinner](functions/Spinner.md)
* [Switch](functions/Switch.md)
* [Table](functions/Table.md)
* [TableHeader](functions/TableHeader.md)
* [TableBody](functions/TableBody.md)
* [TableFooter](functions/TableFooter.md)
* [TableRow](functions/TableRow.md)
* [TableHead](functions/TableHead.md)
* [TableCell](functions/TableCell.md)
* [TableCaption](functions/TableCaption.md)
* [Tabs](functions/Tabs.md)
* [TabsList](functions/TabsList.md)
* [TabsTrigger](functions/TabsTrigger.md)
* [TabsContent](functions/TabsContent.md)
* [Textarea](functions/Textarea.md)
* [ThemeSwitch](functions/ThemeSwitch.md)
* [ToastProvider](functions/ToastProvider.md)
* [ToastViewport](functions/ToastViewport.md)
* [Toast](functions/Toast.md)
* [ToastAction](functions/ToastAction.md)
* [ToastClose](functions/ToastClose.md)
* [ToastTitle](functions/ToastTitle.md)
* [ToastDescription](functions/ToastDescription.md)
* [Toaster](functions/Toaster.md)
* [ToggleGroup](functions/ToggleGroup.md)
* [ToggleGroupItem](functions/ToggleGroupItem.md)
* [toggleVariants](functions/toggleVariants.md)
* [Toggle](functions/Toggle.md)
* [TooltipProvider](functions/TooltipProvider.md)
* [Tooltip](functions/Tooltip.md)
* [TooltipTrigger](functions/TooltipTrigger.md)
* [TooltipContent](functions/TooltipContent.md)
* [Tree](functions/Tree.md)
* [reducer](functions/reducer.md)
* [useToast](functions/useToast.md)
* [useAspectRatioDimensions](functions/useAspectRatioDimensions.md)
* [useDisclosure](functions/useDisclosure.md)
* [useRelativeCoordinates](functions/useRelativeCoordinates.md)
* [cn](functions/cn.md)
* [sqlroomsTailwindPreset](functions/sqlroomsTailwindPreset.md)
* [ThemeProvider](functions/ThemeProvider.md)
* [useTheme](functions/useTheme.md)
## References
### toast
Re-exports [toast](functions/useToast.md#toast)
---
---
url: /api/utils.md
---
# @sqlrooms/utils
A collection of utility functions and helpers for SQLRooms applications. This package provides common utilities for string manipulation, file handling, color management, formatting, and more.
## Features
* 🔠 **String Utilities**: Functions for string manipulation and formatting
* 📁 **File Path Handling**: Tools for working with file paths and extensions
* 🎨 **Color Utilities**: Color conversion and manipulation functions
* 📊 **Formatting**: Data formatting for display purposes
* 🔄 **XHR Helpers**: Utilities for working with XMLHttpRequests
* 🧰 **General Helpers**: Common helper functions for everyday tasks
## Installation
```bash
npm install @sqlrooms/utils
# or
yarn add @sqlrooms/utils
```
## Basic Usage
### String Utilities
```tsx
import {truncate, capitalize, slugify} from '@sqlrooms/utils';
// Truncate long text
const shortText = truncate(
'This is a very long text that needs to be shortened',
20,
);
console.log(shortText); // 'This is a very long...'
// Capitalize text
const capitalized = capitalize('hello world');
console.log(capitalized); // 'Hello world'
// Create a URL-friendly slug
const slug = slugify('Hello World! This is a test');
console.log(slug); // 'hello-world-this-is-a-test'
```
### File Path Utilities
```tsx
import {getFileExtension, joinPaths, normalizePath} from '@sqlrooms/utils';
// Get file extension
const ext = getFileExtension('document.pdf');
console.log(ext); // 'pdf'
// Join path segments
const fullPath = joinPaths('/base/path', 'subfolder', 'file.txt');
console.log(fullPath); // '/base/path/subfolder/file.txt'
// Normalize a path
const normalized = normalizePath('/path//to/../folder/./file.txt');
console.log(normalized); // '/path/folder/file.txt'
```
### JSON Utilities
```tsx
import {safeJsonParse} from '@sqlrooms/utils';
// Safely parse JSON without throwing exceptions
const result = safeJsonParse('{"name": "John", "age": 30}');
console.log(result); // { name: 'John', age: 30 }
// Handle invalid JSON gracefully
const invalid = safeJsonParse('{"name": "John", age: 30}');
console.log(invalid); // undefined
```
### Formatting Utilities
```tsx
import {formatBytes, formatNumber, formatDate} from '@sqlrooms/utils';
// Format file size
console.log(formatBytes(1024)); // '1 KB'
console.log(formatBytes(1048576)); // '1 MB'
// Format numbers
console.log(formatNumber(1234567.89)); // '1,234,567.89'
// Format dates
console.log(formatDate(new Date(), 'yyyy-MM-dd')); // '2023-04-15'
```
## Advanced Features
* **Type Safety**: All utilities are fully typed with TypeScript
* **Browser Compatibility**: Works in all modern browsers
* **Tree-Shakable**: Import only what you need to minimize bundle size
* **No Dependencies**: Zero external runtime dependencies
For more information, visit the SQLRooms documentation.
## Type Aliases
* [ProgressInfo](type-aliases/ProgressInfo.md)
## Variables
* [NUMBER\_FORMAT](variables/NUMBER_FORMAT.md)
## Functions
* [isMacOS](functions/isMacOS.md)
* [opacifyHex](functions/opacifyHex.md)
* [splitFilePath](functions/splitFilePath.md)
* [convertToValidColumnOrTableName](functions/convertToValidColumnOrTableName.md)
* [convertToUniqueColumnOrTableName](functions/convertToUniqueColumnOrTableName.md)
* [generateUniqueName](functions/generateUniqueName.md)
* [generateUniquePath](functions/generateUniquePath.md)
* [convertToUniqueS3ObjectName](functions/convertToUniqueS3ObjectName.md)
* [convertToUniqueS3FolderPath](functions/convertToUniqueS3FolderPath.md)
* [formatCount](functions/formatCount.md)
* [formatCount4](functions/formatCount4.md)
* [formatCountShort](functions/formatCountShort.md)
* [shorten](functions/shorten.md)
* [formatNumber](functions/formatNumber.md)
* [formatDateTime](functions/formatDateTime.md)
* [formatDate](functions/formatDate.md)
* [formatTimeOfDay](functions/formatTimeOfDay.md)
* [formatTimeRelative](functions/formatTimeRelative.md)
* [formatTimestampForFilename](functions/formatTimestampForFilename.md)
* [getErrorMessageForDisplay](functions/getErrorMessageForDisplay.md)
* [safeJsonParse](functions/safeJsonParse.md)
* [memoizeOnce](functions/memoizeOnce.md)
* [genRandomStr](functions/genRandomStr.md)
* [formatBytes](functions/formatBytes.md)
* [camelCaseToTitle](functions/camelCaseToTitle.md)
* [capitalize](functions/capitalize.md)
* [truncate](functions/truncate.md)
* [postData](functions/postData.md)
* [downloadFile](functions/downloadFile.md)
* [uploadFile](functions/uploadFile.md)
---
---
url: /api/vega.md
---
# @sqlrooms/vega
A package that provides Vega-Lite visualization components for the SQLRooms framework, allowing you to create interactive data visualizations directly from SQL queries.
## About Vega-Lite
[Vega-Lite](https://vega.github.io/vega-lite/) is a high-level grammar of interactive graphics. It provides a concise, declarative JSON syntax to create an expressive range of visualizations for data analysis and presentation.
Vega-Lite specifications describe visualizations as encoding mappings from data to properties of graphical marks (e.g., points or bars). The Vega-Lite compiler automatically produces visualization components including axes, legends, and scales. This approach allows for concise specifications while giving users control to customize various parts of a visualization.
This package integrates Vega-Lite with SQLRooms, allowing you to easily create data visualizations directly from SQL queries.
## Components
### VegaLiteChart
A React component that renders a Vega-Lite chart with SQL data and responsive sizing.
#### Features
* **SQL-Powered**: Directly use SQL queries to fetch data for your visualizations
* **Responsive Design**: Multiple sizing options to fit any layout
* **Aspect Ratio Control**: Maintain visual consistency with customizable aspect ratios
* **Integration with DuckDB**: Seamlessly works with the SQLRooms DuckDB integration
#### Installation
```bash
npm install @sqlrooms/vega
# or
yarn add @sqlrooms/vega
```
#### Usage
```tsx
import {VegaLiteChart} from '@sqlrooms/vega';
// Basic usage
function MyChart() {
return (
);
}
```
#### Props
| Prop | Type | Default | Description |
| ------------- | ----------------------------- | ----------- | --------------------------------------------------------------------- |
| `sqlQuery` | `string` | (required) | The SQL query to fetch data for the chart |
| `spec` | `string \| VisualizationSpec` | (required) | The Vega-Lite specification for the chart |
| `width` | `number \| 'auto'` | `'auto'` | The chart width in pixels, or 'auto' to use container width |
| `height` | `number \| 'auto'` | `'auto'` | The chart height in pixels, or 'auto' to calculate from aspect ratio |
| `aspectRatio` | `number` | `3/2` | The desired width-to-height ratio when dimensions are auto-calculated |
| `className` | `string` | `undefined` | Additional CSS classes to apply to the container |
#### Sizing Options
The chart can be sized in multiple ways:
* **Fixed dimensions**: Provide both width and height as numbers
* **Fixed width, proportional height**: Provide width as number, height as 'auto'
* **Fixed height, proportional width**: Provide height as number, width as 'auto'
* **Fully responsive**: Leave both as 'auto' (default), chart will fill container while maintaining aspect ratio
#### Examples
**Fixed size chart:**
```tsx
```
**Responsive chart with 16:9 aspect ratio:**
```tsx
```
### VegaChartTool
A tool for creating Vega-Lite charts in AI-assisted workflows, designed to work with the [SQLRooms AI assistant framework](/api/ai/).
#### Features
* **AI Integration**: Allows AI assistants to create data visualizations
* **SQL-Powered**: Uses SQL queries to fetch data for visualizations
* **Declarative Specs**: Uses Vega-Lite's declarative JSON syntax for chart creation
* **Responsive Design**: Charts automatically adapt to container size
#### Usage
```tsx
import {createVegaChartTool} from '@sqlrooms/vega';
import {createAiSlice} from '@sqlrooms/ai';
import {createRoomStore} from '@sqlrooms/room-shell';
// Create a room store with the VegaChartTool configured
export const {roomStore, useRoomStore} = createRoomStore((set, get, store) => ({
// Other slices and state...
// AI slice with custom tools
...createAiSlice({
getApiKey: (modelProvider: string) => {
return get()?.apiKeys[modelProvider] || '';
},
// Configure custom tools at store creation time
customTools: {
// Add the VegaChart tool
chart: createVegaChartTool({
// Optional custom description
description:
'Create data visualizations using Vega-Lite and SQL queries',
}),
// Other custom tools...
},
})(set, get, store),
// Other state and methods...
}));
```
#### Tool Parameters
The VegaChartTool accepts the following parameters:
| Parameter | Type | Description |
| -------------- | -------- | ----------------------------------------------------------- |
| `sqlQuery` | `string` | The SQL query to fetch data for the chart |
| `vegaLiteSpec` | `string` | The Vega-Lite specification as a JSON string |
| `reasoning` | `string` | Optional explanation of the chart's purpose or significance |
#### Example AI Assistant Usage
When the AI assistant uses the VegaChartTool, it will generate a response like this:
```json
{
"sqlQuery": "SELECT product_category, SUM(sales) as total_sales FROM sales GROUP BY product_category ORDER BY total_sales DESC LIMIT 10",
"vegaLiteSpec": "{\"mark\": \"bar\", \"encoding\": {\"x\": {\"field\": \"product_category\", \"type\": \"nominal\", \"sort\": \"-y\"}, \"y\": {\"field\": \"total_sales\", \"type\": \"quantitative\", \"title\": \"Total Sales\"}, \"color\": {\"field\": \"product_category\", \"type\": \"nominal\", \"legend\": null}}}",
"reasoning": "This chart visualizes the top 10 product categories by total sales to identify the best-performing categories."
}
```
In a conversation with the AI assistant, it might look like this:
```
User: Can you show me a chart of our top 10 product categories by sales?
AI: I'll create a visualization of your top 10 product categories by sales.
[Chart: Bar chart showing product categories on the x-axis and total sales on the y-axis]
This chart displays your top 10 product categories ranked by total sales. As you can see,
Electronics leads with the highest sales, followed by Furniture and Clothing. This visualization
helps identify which product categories are driving the most revenue for your business.
```
The tool will:
1. Execute the SQL query to fetch the data
2. Apply the Vega-Lite specification to create the visualization
3. Render the chart in the UI with responsive sizing
## Dependencies
This package depends on:
* `@sqlrooms/duckdb` - For SQL query execution
* `@sqlrooms/ui` - For UI utilities
* `@sqlrooms/utils` - For utility functions
* `@sqlrooms/ai` - For AI assistant integration
* `react-vega` - For rendering Vega-Lite visualizations
## Type Aliases
* [VisualizationSpec](type-aliases/VisualizationSpec.md)
* [VegaChartToolParameters](type-aliases/VegaChartToolParameters.md)
## Variables
* [VegaChartToolParameters](variables/VegaChartToolParameters.md)
* [DEFAULT\_VEGA\_CHART\_DESCRIPTION](variables/DEFAULT_VEGA_CHART_DESCRIPTION.md)
## Functions
* [createVegaChartTool](functions/createVegaChartTool.md)
* [VegaChartToolResult](functions/VegaChartToolResult.md)
* [VegaLiteChart](functions/VegaLiteChart.md)
## References
### VegaChartToolParametersType
Renames and re-exports [VegaChartToolParameters](variables/VegaChartToolParameters.md)
---
---
url: /api/recharts/namespaces/CartesianGrid.md
---
[@sqlrooms/recharts](../../index.md) / CartesianGrid
# CartesianGrid
## Variables
* [displayName](variables/displayName.md)
---
---
url: /case-studies.md
---
# Case Studies
## Foursquare Spatial Desktop
[Foursquare Spatial Desktop](https://foursquare.com/products/spatial-desktop) is a powerful geospatial computing tool that transforms your desktop into a comprehensive spatial analysis environment. Built on SQLRooms, it delivers native DuckDB query performance and real-time visualization rendering—all powered natively on your machine without requiring server infrastructure.
[\](https://foursquare.com/products/spatial-desktop/)
Key features include:
* **Native DuckDB Performance**: Run complex spatial queries on multi-GB datasets with native DuckDB integration without cloud compute dependence
* **Real-time Rendering**: Harness Kepler.gl's visualization excellence to render millions of points with interactive filtering and smooth animations
* **Modern Spatial Formats**: Native support for GeoParquet, PMTiles, and other formats GIS professionals need
* **Flexible Data Management**: Save projects locally or to personal cloud storage without internet connectivity requirements
* **Offline Capability**: Full analytical power available without cloud dependencies
## Flowmap City
[Flowmap City](https://www.flowmap.city/) is a powerful web-based platform for visualizing and analyzing mobility data and origin-destination flows. The application helps urban planners, transportation analysts, and researchers understand movement patterns in cities and regions.
[\](https://www.flowmap.city/)
The platform enables users to upload their own mobility datasets and create interactive visualizations that can be shared with stakeholders or embedded in other applications.
Key features include:
* **Flow Visualization**: Analyze origin-destination patterns with interactive flow maps
* **Mobility Analysis**: Study commuting patterns, transportation demand, and traffic flows
* **Temporal Patterns**: Explore how movement patterns change over time and seasons
* **Multi-modal Analysis**: Compare different transportation modes and their usage
* **Infrastructure Planning**: Make data-driven decisions for transportation infrastructure
* **Interactive Filtering**: Filter and analyze specific routes, regions, or time periods
## Cosmograph
[Cosmograph](https://cosmograph.app/) is a powerful web-based application for visualizing and analyzing large graph datasets and machine learning embeddings. The application runs entirely in the browser, leveraging your GPU for all computations while keeping your data private and secure. The upcoming version of Cosmograph is being built using SQLRooms to enhance its data processing capabilities and analytical features.
[\](https://run.cosmograph.app/)
Key features include:
* **Network Graph Visualization**: Analyze complex relationships and patterns in graph data
* **ML Embeddings Analysis**: Visualize and explore machine learning embeddings in 2D space
* **Temporal Analysis**: Study how relationships and patterns evolve over time
* **Community Detection**: Identify clusters and anomalies within your data
* **Interactive Analysis**: Use filters and histograms to explore data distributions
* **GPU-Accelerated**: Performs all calculations locally using your GPU for optimal performance
---
---
url: /api/recharts/classes/Area.md
---
[@sqlrooms/recharts](../index.md) / Area
# Class: Area
## Extends
* `PureComponent`<[`AreaProps`](../type-aliases/AreaProps.md), `State`>
## Constructors
### new Area()
> **new Area**(`props`): [`Area`](Area.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`AreaProps`](../type-aliases/AreaProps.md) |
#### Returns
[`Area`](Area.md)
#### Inherited from
`PureComponent.constructor`
### new Area()
> **new Area**(`props`, `context`): [`Area`](Area.md)
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `props` | [`AreaProps`](../type-aliases/AreaProps.md) | |
| `context` | `any` | value of the parent [Context](https://react.dev/reference/react/Component#context) specified in `contextType`. |
#### Returns
[`Area`](Area.md)
#### Inherited from
`PureComponent.constructor`
## Properties
| Property | Modifier | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | - | `PureComponent.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | - | `PureComponent.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | - | `PureComponent.context` |
| `props` | `readonly` | `Readonly`<[`AreaProps`](../type-aliases/AreaProps.md)> | - | - | `PureComponent.props` |
| `displayName` | `static` | `string` | - | - | - |
| `defaultProps` | `static` | `object` | - | - | - |
| `defaultProps.stroke` | `public` | `string` | - | - | - |
| `defaultProps.fill` | `public` | `string` | - | - | - |
| `defaultProps.fillOpacity` | `public` | `number` | - | - | - |
| `defaultProps.xAxisId` | `public` | `number` | - | - | - |
| `defaultProps.yAxisId` | `public` | `number` | - | - | - |
| `defaultProps.legendType` | `public` | `string` | - | - | - |
| `defaultProps.connectNulls` | `public` | `boolean` | - | - | - |
| `defaultProps.points` | `public` | `AreaPointItem`\[] | - | - | - |
| `defaultProps.dot` | `public` | `boolean` | - | - | - |
| `defaultProps.activeDot` | `public` | `boolean` | - | - | - |
| `defaultProps.hide` | `public` | `boolean` | - | - | - |
| `defaultProps.isAnimationActive` | `public` | `boolean` | - | - | - |
| `defaultProps.animationBegin` | `public` | `number` | - | - | - |
| `defaultProps.animationDuration` | `public` | `number` | - | - | - |
| `defaultProps.animationEasing` | `public` | `string` | - | - | - |
| `getBaseValue` | `static` | (`props`: [`AreaProps`](../type-aliases/AreaProps.md), `item`: [`Area`](Area.md), `xAxis`: `undefined` | `Omit`<[`XAxisProps`](../type-aliases/XAxisProps.md), `"scale"`> & `object`, `yAxis`: `undefined` | `Omit`<[`YAxisProps`](../type-aliases/YAxisProps.md), `"scale"`> & `object`) => `number` | - | - | - |
| `getComposedData` | `static` | (`__namedParameters`: `object`) => `object` | - | - | - |
| `renderDotItem` | `static` | (`option`: `AreaDot`, `props`: `any`) => `Element` | - | - | - |
| `state` | `public` | `State` | - | `PureComponent.state` | - |
| `id` | `public` | `string` | - | - | - |
| `handleAnimationEnd` | `public` | () => `void` | - | - | - |
| `handleAnimationStart` | `public` | () => `void` | - | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* keyof `State` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | `State` | (`prevState`, `props`) => `null` | `State` | `Pick`<`State`, `K`> | `Pick`<`State`, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.forceUpdate`
***
### componentDidMount()?
> `optional` **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidMount`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`AreaProps`](../type-aliases/AreaProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`PureComponent.shouldComponentUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`PureComponent.componentWillUnmount`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](Area.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`AreaProps`](../type-aliases/AreaProps.md)> |
| `prevState` | `Readonly`<`State`> |
#### Returns
`any`
#### Inherited from
`PureComponent.getSnapshotBeforeUpdate`
***
### componentDidUpdate()?
> `optional` **componentDidUpdate**(`prevProps`, `prevState`, `snapshot`?): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](Area.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`AreaProps`](../type-aliases/AreaProps.md)> |
| `prevState` | `Readonly`<`State`> |
| `snapshot`? | `any` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`AreaProps`](../type-aliases/AreaProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`AreaProps`](../type-aliases/AreaProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`AreaProps`](../type-aliases/AreaProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`AreaProps`](../type-aliases/AreaProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillUpdate`
***
### getDerivedStateFromProps()
> `static` **getDerivedStateFromProps**(`nextProps`, `prevState`): `State`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | [`AreaProps`](../type-aliases/AreaProps.md) |
| `prevState` | `State` |
#### Returns
`State`
***
### renderDots()
> **renderDots**(`needClip`, `clipDot`, `clipPathId`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `needClip` | `boolean` |
| `clipDot` | `boolean` |
| `clipPathId` | `string` |
#### Returns
`Element`
***
### renderHorizontalRect()
> **renderHorizontalRect**(`alpha`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `alpha` | `number` |
#### Returns
`Element`
***
### renderVerticalRect()
> **renderVerticalRect**(`alpha`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `alpha` | `number` |
#### Returns
`Element`
***
### renderClipRect()
> **renderClipRect**(`alpha`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `alpha` | `number` |
#### Returns
`Element`
***
### renderAreaStatically()
> **renderAreaStatically**(`points`, `baseLine`, `needClip`, `clipPathId`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `points` | `AreaPointItem`\[] |
| `baseLine` | `undefined` | `number` | `Coordinate`\[] |
| `needClip` | `boolean` |
| `clipPathId` | `string` |
#### Returns
`Element`
***
### renderAreaWithAnimation()
> **renderAreaWithAnimation**(`needClip`, `clipPathId`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `needClip` | `boolean` |
| `clipPathId` | `string` |
#### Returns
`Element`
***
### renderArea()
> **renderArea**(`needClip`, `clipPathId`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `needClip` | `boolean` |
| `clipPathId` | `string` |
#### Returns
`Element`
***
### render()
> **render**(): `Element`
#### Returns
`Element`
#### Overrides
`PureComponent.render`
---
---
url: /api/recharts/classes/Bar.md
---
[@sqlrooms/recharts](../index.md) / Bar
# Class: Bar
## Extends
* `PureComponent`<[`BarProps`](../type-aliases/BarProps.md), `State`>
## Constructors
### new Bar()
> **new Bar**(`props`): [`Bar`](Bar.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`BarProps`](../type-aliases/BarProps.md) |
#### Returns
[`Bar`](Bar.md)
#### Inherited from
`PureComponent.constructor`
### new Bar()
> **new Bar**(`props`, `context`): [`Bar`](Bar.md)
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `props` | [`BarProps`](../type-aliases/BarProps.md) | |
| `context` | `any` | value of the parent [Context](https://react.dev/reference/react/Component#context) specified in `contextType`. |
#### Returns
[`Bar`](Bar.md)
#### Inherited from
`PureComponent.constructor`
## Properties
| Property | Modifier | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | - | `PureComponent.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | - | `PureComponent.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | - | `PureComponent.context` |
| `props` | `readonly` | `Readonly`<[`BarProps`](../type-aliases/BarProps.md)> | - | - | `PureComponent.props` |
| `displayName` | `static` | `string` | - | - | - |
| `defaultProps` | `static` | `object` | - | - | - |
| `defaultProps.xAxisId` | `public` | `number` | - | - | - |
| `defaultProps.yAxisId` | `public` | `number` | - | - | - |
| `defaultProps.legendType` | `public` | `string` | - | - | - |
| `defaultProps.minPointSize` | `public` | `number` | - | - | - |
| `defaultProps.hide` | `public` | `boolean` | - | - | - |
| `defaultProps.data` | `public` | `BarRectangleItem`\[] | - | - | - |
| `defaultProps.layout` | `public` | `string` | - | - | - |
| `defaultProps.activeBar` | `public` | `boolean` | - | - | - |
| `defaultProps.isAnimationActive` | `public` | `boolean` | - | - | - |
| `defaultProps.animationBegin` | `public` | `number` | - | - | - |
| `defaultProps.animationDuration` | `public` | `number` | - | - | - |
| `defaultProps.animationEasing` | `public` | `string` | - | - | - |
| `getComposedData` | `static` | (`__namedParameters`: `object`) => `object` | Compose the data of each group | - | - |
| `state` | `public` | `State` | - | `PureComponent.state` | - |
| `id` | `public` | `string` | - | - | - |
| `handleAnimationEnd` | `public` | () => `void` | - | - | - |
| `handleAnimationStart` | `public` | () => `void` | - | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* keyof `State` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | `State` | (`prevState`, `props`) => `null` | `State` | `Pick`<`State`, `K`> | `Pick`<`State`, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.forceUpdate`
***
### componentDidMount()?
> `optional` **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidMount`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`BarProps`](../type-aliases/BarProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`PureComponent.shouldComponentUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`PureComponent.componentWillUnmount`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](Bar.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`BarProps`](../type-aliases/BarProps.md)> |
| `prevState` | `Readonly`<`State`> |
#### Returns
`any`
#### Inherited from
`PureComponent.getSnapshotBeforeUpdate`
***
### componentDidUpdate()?
> `optional` **componentDidUpdate**(`prevProps`, `prevState`, `snapshot`?): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](Bar.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`BarProps`](../type-aliases/BarProps.md)> |
| `prevState` | `Readonly`<`State`> |
| `snapshot`? | `any` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`BarProps`](../type-aliases/BarProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`BarProps`](../type-aliases/BarProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`BarProps`](../type-aliases/BarProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`BarProps`](../type-aliases/BarProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillUpdate`
***
### getDerivedStateFromProps()
> `static` **getDerivedStateFromProps**(`nextProps`, `prevState`): `State`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | [`BarProps`](../type-aliases/BarProps.md) |
| `prevState` | `State` |
#### Returns
`State`
***
### renderRectanglesStatically()
> **renderRectanglesStatically**(`data`): `Element`\[]
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `data` | `BarRectangleItem`\[] |
#### Returns
`Element`\[]
***
### renderRectanglesWithAnimation()
> **renderRectanglesWithAnimation**(): `Element`
#### Returns
`Element`
***
### renderRectangles()
> **renderRectangles**(): `Element` | `Element`\[]
#### Returns
`Element` | `Element`\[]
***
### renderBackground()
> **renderBackground**(): `Element`\[]
#### Returns
`Element`\[]
***
### renderErrorBar()
> **renderErrorBar**(`needClip`, `clipPathId`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `needClip` | `boolean` |
| `clipPathId` | `string` |
#### Returns
`Element`
***
### render()
> **render**(): `Element`
#### Returns
`Element`
#### Overrides
`PureComponent.render`
---
---
url: /api/recharts/classes/Brush.md
---
[@sqlrooms/recharts](../index.md) / Brush
# Class: Brush
## Extends
* `PureComponent`<[`BrushProps`](../type-aliases/BrushProps.md), `State`>
## Constructors
### new Brush()
> **new Brush**(`props`): [`Brush`](Brush.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`BrushProps`](../type-aliases/BrushProps.md) |
#### Returns
[`Brush`](Brush.md)
#### Overrides
`PureComponent.constructor`
## Properties
| Property | Modifier | Type | Description | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | `PureComponent.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | `PureComponent.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | `PureComponent.context` |
| `props` | `readonly` | `Readonly`<[`BrushProps`](../type-aliases/BrushProps.md)> | - | `PureComponent.props` |
| `state` | `public` | `Readonly`<`State`> | - | `PureComponent.state` |
| `displayName` | `static` | `string` | - | - |
| `defaultProps` | `static` | `object` | - | - |
| `defaultProps.height` | `public` | `number` | - | - |
| `defaultProps.travellerWidth` | `public` | `number` | - | - |
| `defaultProps.gap` | `public` | `number` | - | - |
| `defaultProps.fill` | `public` | `string` | - | - |
| `defaultProps.stroke` | `public` | `string` | - | - |
| `defaultProps.padding` | `public` | `object` | - | - |
| `defaultProps.padding.top` | `public` | `number` | - | - |
| `defaultProps.padding.right` | `public` | `number` | - | - |
| `defaultProps.padding.bottom` | `public` | `number` | - | - |
| `defaultProps.padding.left` | `public` | `number` | - | - |
| `defaultProps.leaveTimeOut` | `public` | `number` | - | - |
| `defaultProps.alwaysShowText` | `public` | `boolean` | - | - |
| `leaveTimer?` | `public` | `number` | - | - |
| `travellerDragStartHandlers?` | `public` | `Record`<`BrushTravellerId`, (`event`) => `void`> | - | - |
| `handleDrag` | `public` | (`e`: `MouseEvent` | `MouseEvent`<`SVGGElement`, `MouseEvent`> | `Touch`) => `void` | - | - |
| `handleTouchMove` | `public` | (`e`: `TouchEvent`<`SVGGElement`>) => `void` | - | - |
| `handleDragEnd` | `public` | () => `void` | - | - |
| `handleLeaveWrapper` | `public` | () => `void` | - | - |
| `handleEnterSlideOrTraveller` | `public` | () => `void` | - | - |
| `handleLeaveSlideOrTraveller` | `public` | () => `void` | - | - |
| `handleSlideDragStart` | `public` | (`e`: `TouchEvent`<`SVGRectElement`> | `MouseEvent`<`SVGRectElement`, `MouseEvent`>) => `void` | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* keyof `State` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | `State` | (`prevState`, `props`) => `null` | `State` | `Pick`<`State`, `K`> | `Pick`<`State`, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.forceUpdate`
***
### componentDidMount()?
> `optional` **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidMount`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`BrushProps`](../type-aliases/BrushProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`PureComponent.shouldComponentUpdate`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](Brush.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`BrushProps`](../type-aliases/BrushProps.md)> |
| `prevState` | `Readonly`<`State`> |
#### Returns
`any`
#### Inherited from
`PureComponent.getSnapshotBeforeUpdate`
***
### componentDidUpdate()?
> `optional` **componentDidUpdate**(`prevProps`, `prevState`, `snapshot`?): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](Brush.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`BrushProps`](../type-aliases/BrushProps.md)> |
| `prevState` | `Readonly`<`State`> |
| `snapshot`? | `any` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`BrushProps`](../type-aliases/BrushProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`BrushProps`](../type-aliases/BrushProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`BrushProps`](../type-aliases/BrushProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`BrushProps`](../type-aliases/BrushProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillUpdate`
***
### renderDefaultTraveller()
> `static` **renderDefaultTraveller**(`props`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | `any` |
#### Returns
`Element`
***
### renderTraveller()
> `static` **renderTraveller**(`option`, `props`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `option` | `BrushTravellerType` |
| `props` | `any` |
#### Returns
`Element`
***
### getDerivedStateFromProps()
> `static` **getDerivedStateFromProps**(`nextProps`, `prevState`): `State`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | [`BrushProps`](../type-aliases/BrushProps.md) |
| `prevState` | `State` |
#### Returns
`State`
***
### componentWillUnmount()
> **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Overrides
`PureComponent.componentWillUnmount`
***
### getIndexInRange()
> `static` **getIndexInRange**(`valueRange`, `x`): `number`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `valueRange` | `number`\[] |
| `x` | `number` |
#### Returns
`number`
***
### getIndex()
> **getIndex**(`__namedParameters`): `object`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `__namedParameters` | { `startX`: `number`; `endX`: `number`; } |
| `__namedParameters.startX` | `number` |
| `__namedParameters.endX` | `number` |
#### Returns
`object`
| Name | Type |
| ------ | ------ |
| `startIndex` | `number` |
| `endIndex` | `number` |
***
### getTextOfTick()
> **getTextOfTick**(`index`): `any`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `index` | `number` |
#### Returns
`any`
***
### attachDragEndListener()
> **attachDragEndListener**(): `void`
#### Returns
`void`
***
### detachDragEndListener()
> **detachDragEndListener**(): `void`
#### Returns
`void`
***
### handleSlideDrag()
> **handleSlideDrag**(`e`): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `e` | `MouseEvent` | `MouseEvent`<`SVGGElement`, `MouseEvent`> | `Touch` |
#### Returns
`void`
***
### handleTravellerDragStart()
> **handleTravellerDragStart**(`id`, `e`): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `id` | `BrushTravellerId` |
| `e` | `MouseEvent`<`SVGGElement`, `MouseEvent`> | `TouchEvent`<`SVGGElement`> |
#### Returns
`void`
***
### handleTravellerMove()
> **handleTravellerMove**(`e`): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `e` | `MouseEvent` | `MouseEvent`<`SVGGElement`, `MouseEvent`> | `Touch` |
#### Returns
`void`
***
### handleTravellerMoveKeyboard()
> **handleTravellerMoveKeyboard**(`direction`, `id`): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `direction` | `-1` | `1` |
| `id` | `BrushTravellerId` |
#### Returns
`void`
***
### renderBackground()
> **renderBackground**(): `Element`
#### Returns
`Element`
***
### renderPanorama()
> **renderPanorama**(): `ReactElement`<`any`, `string` | `JSXElementConstructor`<`any`>>
#### Returns
`ReactElement`<`any`, `string` | `JSXElementConstructor`<`any`>>
***
### renderTravellerLayer()
> **renderTravellerLayer**(`travellerX`, `id`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `travellerX` | `number` |
| `id` | `BrushTravellerId` |
#### Returns
`Element`
***
### renderSlide()
> **renderSlide**(`startX`, `endX`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `startX` | `number` |
| `endX` | `number` |
#### Returns
`Element`
***
### renderText()
> **renderText**(): `Element`
#### Returns
`Element`
***
### render()
> **render**(): `Element`
#### Returns
`Element`
#### Overrides
`PureComponent.render`
---
---
url: /api/recharts/classes/CartesianAxis.md
---
[@sqlrooms/recharts](../index.md) / CartesianAxis
# Class: CartesianAxis
## Extends
* `Component`<[`CartesianAxisProps`](../type-aliases/CartesianAxisProps.md), `IState`>
## Constructors
### new CartesianAxis()
> **new CartesianAxis**(`props`): [`CartesianAxis`](CartesianAxis.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`CartesianAxisProps`](../type-aliases/CartesianAxisProps.md) |
#### Returns
[`CartesianAxis`](CartesianAxis.md)
#### Overrides
`Component.constructor`
## Properties
| Property | Modifier | Type | Description | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | `Component.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | `Component.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | `Component.context` |
| `props` | `readonly` | `Readonly`<[`CartesianAxisProps`](../type-aliases/CartesianAxisProps.md)> | - | `Component.props` |
| `state` | `public` | `Readonly`<`IState`> | - | `Component.state` |
| `displayName` | `static` | `string` | - | - |
| `defaultProps` | `static` | `object` | - | - |
| `defaultProps.x` | `public` | `number` | - | - |
| `defaultProps.y` | `public` | `number` | - | - |
| `defaultProps.width` | `public` | `number` | - | - |
| `defaultProps.height` | `public` | `number` | - | - |
| `defaultProps.viewBox` | `public` | `object` | - | - |
| `defaultProps.viewBox.x` | `public` | `number` | - | - |
| `defaultProps.viewBox.y` | `public` | `number` | - | - |
| `defaultProps.viewBox.width` | `public` | `number` | - | - |
| `defaultProps.viewBox.height` | `public` | `number` | - | - |
| `defaultProps.orientation` | `public` | `string` | - | - |
| `defaultProps.ticks` | `public` | `CartesianTickItem`\[] | - | - |
| `defaultProps.stroke` | `public` | `string` | - | - |
| `defaultProps.tickLine` | `public` | `boolean` | - | - |
| `defaultProps.axisLine` | `public` | `boolean` | - | - |
| `defaultProps.tick` | `public` | `boolean` | - | - |
| `defaultProps.mirror` | `public` | `boolean` | - | - |
| `defaultProps.minTickGap` | `public` | `number` | - | - |
| `defaultProps.tickSize` | `public` | `number` | - | - |
| `defaultProps.tickMargin` | `public` | `number` | - | - |
| `defaultProps.interval` | `public` | `string` | - | - |
| `layerReference` | `private` | `any` | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* keyof `IState` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | `IState` | (`prevState`, `props`) => `null` | `IState` | `Pick`<`IState`, `K`> | `Pick`<`IState`, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`Component.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`Component.forceUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`Component.componentWillUnmount`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`Component.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](CartesianAxis.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`CartesianAxisProps`](../type-aliases/CartesianAxisProps.md)> |
| `prevState` | `Readonly`<`IState`> |
#### Returns
`any`
#### Inherited from
`Component.getSnapshotBeforeUpdate`
***
### componentDidUpdate()?
> `optional` **componentDidUpdate**(`prevProps`, `prevState`, `snapshot`?): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](CartesianAxis.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`CartesianAxisProps`](../type-aliases/CartesianAxisProps.md)> |
| `prevState` | `Readonly`<`IState`> |
| `snapshot`? | `any` |
#### Returns
`void`
#### Inherited from
`Component.componentDidUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`Component.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`Component.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`CartesianAxisProps`](../type-aliases/CartesianAxisProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`Component.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`CartesianAxisProps`](../type-aliases/CartesianAxisProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`Component.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`CartesianAxisProps`](../type-aliases/CartesianAxisProps.md)> |
| `nextState` | `Readonly`<`IState`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`Component.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`CartesianAxisProps`](../type-aliases/CartesianAxisProps.md)> |
| `nextState` | `Readonly`<`IState`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`Component.UNSAFE_componentWillUpdate`
***
### shouldComponentUpdate()
> **shouldComponentUpdate**(`__namedParameters`, `nextState`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `__namedParameters` | [`CartesianAxisProps`](../type-aliases/CartesianAxisProps.md) |
| `nextState` | `IState` |
#### Returns
`boolean`
#### Overrides
`Component.shouldComponentUpdate`
***
### componentDidMount()
> **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Overrides
`Component.componentDidMount`
***
### getTickLineCoord()
> **getTickLineCoord**(`data`): `object`
Calculate the coordinates of endpoints in ticks
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `data` | `CartesianTickItem` | The data of a simple tick |
#### Returns
`object`
(x1, y1): The coordinate of endpoint close to tick text
(x2, y2): The coordinate of endpoint close to axis
| Name | Type |
| ------ | ------ |
| `line` | { `x1`: `number`; `y1`: `number`; `x2`: `number`; `y2`: `number`; } |
| `tick` | { `x`: `number`; `y`: `number`; } |
***
### getTickTextAnchor()
> **getTickTextAnchor**(): `string`
#### Returns
`string`
***
### getTickVerticalAnchor()
> **getTickVerticalAnchor**(): `string`
#### Returns
`string`
***
### renderAxisLine()
> **renderAxisLine**(): `Element`
#### Returns
`Element`
***
### renderTickItem()
> `static` **renderTickItem**(`option`, `props`, `value`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `option` | `undefined` | `boolean` | `SVGProps`<`SVGTextElement`> | `ReactElement`<`SVGElement`, `string` | `JSXElementConstructor`<`any`>> | (`props`) => `ReactElement`<`SVGElement`> |
| `props` | `any` |
| `value` | `ReactNode` |
#### Returns
`Element`
***
### renderTicks()
> **renderTicks**(`ticks`, `fontSize`, `letterSpacing`): `Element`
render the ticks
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `ticks` | `CartesianTickItem`\[] | The ticks to actually render (overrides what was passed in props) |
| `fontSize` | `string` | Fontsize to consider for tick spacing |
| `letterSpacing` | `string` | Letterspacing to consider for tick spacing |
#### Returns
`Element`
renderedTicks
***
### render()
> **render**(): `Element`
#### Returns
`Element`
#### Overrides
`Component.render`
---
---
url: /api/recharts/classes/DefaultLegendContent.md
---
[@sqlrooms/recharts](../index.md) / DefaultLegendContent
# Class: DefaultLegendContent
## Extends
* `PureComponent`<[`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md)>
## Constructors
### new DefaultLegendContent()
> **new DefaultLegendContent**(`props`): [`DefaultLegendContent`](DefaultLegendContent.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md) |
#### Returns
[`DefaultLegendContent`](DefaultLegendContent.md)
#### Inherited from
`PureComponent.constructor`
### new DefaultLegendContent()
> **new DefaultLegendContent**(`props`, `context`): [`DefaultLegendContent`](DefaultLegendContent.md)
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `props` | [`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md) | |
| `context` | `any` | value of the parent [Context](https://react.dev/reference/react/Component#context) specified in `contextType`. |
#### Returns
[`DefaultLegendContent`](DefaultLegendContent.md)
#### Inherited from
`PureComponent.constructor`
## Properties
| Property | Modifier | Type | Description | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | `PureComponent.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | `PureComponent.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | `PureComponent.context` |
| `props` | `readonly` | `Readonly`<[`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md)> | - | `PureComponent.props` |
| `state` | `public` | `Readonly`<{}> | - | `PureComponent.state` |
| `displayName` | `static` | `string` | - | - |
| `defaultProps` | `static` | `object` | - | - |
| `defaultProps.iconSize` | `public` | `number` | - | - |
| `defaultProps.layout` | `public` | `string` | - | - |
| `defaultProps.align` | `public` | `string` | - | - |
| `defaultProps.verticalAlign` | `public` | `string` | - | - |
| `defaultProps.inactiveColor` | `public` | `string` | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* `never` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | {} | (`prevState`, `props`) => `null` | {} | `Pick`<{}, `K`> | `Pick`<{}, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.forceUpdate`
***
### componentDidMount()?
> `optional` **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidMount`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md)> |
| `nextState` | `Readonly`<{}> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`PureComponent.shouldComponentUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`PureComponent.componentWillUnmount`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](DefaultLegendContent.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md)> |
| `prevState` | `Readonly`<{}> |
#### Returns
`any`
#### Inherited from
`PureComponent.getSnapshotBeforeUpdate`
***
### componentDidUpdate()?
> `optional` **componentDidUpdate**(`prevProps`, `prevState`, `snapshot`?): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](DefaultLegendContent.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md)> |
| `prevState` | `Readonly`<{}> |
| `snapshot`? | `any` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md)> |
| `nextState` | `Readonly`<{}> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`DefaultLegendContentProps`](../type-aliases/DefaultLegendContentProps.md)> |
| `nextState` | `Readonly`<{}> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillUpdate`
***
### renderIcon()
> **renderIcon**(`data`): `Element`
Render the path of icon
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `data` | `Payload` | Data of each legend item |
#### Returns
`Element`
Path element
***
### renderItems()
> **renderItems**(): `Element`\[]
Draw items of legend
#### Returns
`Element`\[]
Items
***
### render()
> **render**(): `Element`
#### Returns
`Element`
#### Overrides
`PureComponent.render`
---
---
url: /api/recharts/classes/ErrorBar.md
---
[@sqlrooms/recharts](../index.md) / ErrorBar
# Class: ErrorBar
## Extends
* `Component`<[`ErrorBarProps`](../type-aliases/ErrorBarProps.md)>
## Constructors
### new ErrorBar()
> **new ErrorBar**(`props`): [`ErrorBar`](ErrorBar.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`ErrorBarProps`](../type-aliases/ErrorBarProps.md) |
#### Returns
[`ErrorBar`](ErrorBar.md)
#### Inherited from
`React.Component.constructor`
### new ErrorBar()
> **new ErrorBar**(`props`, `context`): [`ErrorBar`](ErrorBar.md)
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `props` | [`ErrorBarProps`](../type-aliases/ErrorBarProps.md) | |
| `context` | `any` | value of the parent [Context](https://react.dev/reference/react/Component#context) specified in `contextType`. |
#### Returns
[`ErrorBar`](ErrorBar.md)
#### Inherited from
`React.Component.constructor`
## Properties
| Property | Modifier | Type | Description | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | `React.Component.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | `React.Component.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | `React.Component.context` |
| `props` | `readonly` | `Readonly`<[`ErrorBarProps`](../type-aliases/ErrorBarProps.md)> | - | `React.Component.props` |
| `state` | `public` | `Readonly`<{}> | - | `React.Component.state` |
| `defaultProps` | `static` | `object` | - | - |
| `defaultProps.stroke` | `public` | `string` | - | - |
| `defaultProps.strokeWidth` | `public` | `number` | - | - |
| `defaultProps.width` | `public` | `number` | - | - |
| `defaultProps.offset` | `public` | `number` | - | - |
| `defaultProps.layout` | `public` | `string` | - | - |
| `displayName` | `static` | `string` | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* `never` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | {} | (`prevState`, `props`) => `null` | {} | `Pick`<{}, `K`> | `Pick`<{}, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`React.Component.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`React.Component.forceUpdate`
***
### componentDidMount()?
> `optional` **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Inherited from
`React.Component.componentDidMount`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`ErrorBarProps`](../type-aliases/ErrorBarProps.md)> |
| `nextState` | `Readonly`<{}> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`React.Component.shouldComponentUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`React.Component.componentWillUnmount`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`React.Component.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](ErrorBar.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`ErrorBarProps`](../type-aliases/ErrorBarProps.md)> |
| `prevState` | `Readonly`<{}> |
#### Returns
`any`
#### Inherited from
`React.Component.getSnapshotBeforeUpdate`
***
### componentDidUpdate()?
> `optional` **componentDidUpdate**(`prevProps`, `prevState`, `snapshot`?): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](ErrorBar.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`ErrorBarProps`](../type-aliases/ErrorBarProps.md)> |
| `prevState` | `Readonly`<{}> |
| `snapshot`? | `any` |
#### Returns
`void`
#### Inherited from
`React.Component.componentDidUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`React.Component.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`React.Component.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`ErrorBarProps`](../type-aliases/ErrorBarProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`React.Component.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`ErrorBarProps`](../type-aliases/ErrorBarProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`React.Component.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`ErrorBarProps`](../type-aliases/ErrorBarProps.md)> |
| `nextState` | `Readonly`<{}> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`React.Component.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`ErrorBarProps`](../type-aliases/ErrorBarProps.md)> |
| `nextState` | `Readonly`<{}> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`React.Component.UNSAFE_componentWillUpdate`
***
### render()
> **render**(): `Element`
#### Returns
`Element`
#### Overrides
`React.Component.render`
---
---
url: /api/ui/classes/ErrorBoundary.md
---
[@sqlrooms/ui](../index.md) / ErrorBoundary
# Class: ErrorBoundary
## Extends
* `Component`<`Props`, `State`>
## Constructors
### new ErrorBoundary()
> **new ErrorBoundary**(`props`): [`ErrorBoundary`](ErrorBoundary.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | `Props` |
#### Returns
[`ErrorBoundary`](ErrorBoundary.md)
#### Inherited from
`Component.constructor`
### new ErrorBoundary()
> **new ErrorBoundary**(`props`, `context`): [`ErrorBoundary`](ErrorBoundary.md)
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `props` | `Props` | |
| `context` | `any` | value of the parent [Context](https://react.dev/reference/react/Component#context) specified in `contextType`. |
#### Returns
[`ErrorBoundary`](ErrorBoundary.md)
#### Inherited from
`Component.constructor`
## Properties
| Property | Modifier | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | - | `Component.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | - | `Component.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | - | `Component.context` |
| `props` | `readonly` | `Readonly`<`Props`> | - | - | `Component.props` |
| `state` | `public` | `State` | - | `Component.state` | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* keyof `State` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | `State` | (`prevState`, `props`) => `null` | `State` | `Pick`<`State`, `K`> | `Pick`<`State`, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`Component.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`Component.forceUpdate`
***
### componentDidMount()?
> `optional` **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Inherited from
`Component.componentDidMount`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<`Props`> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`Component.shouldComponentUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`Component.componentWillUnmount`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](ErrorBoundary.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<`Props`> |
| `prevState` | `Readonly`<`State`> |
#### Returns
`any`
#### Inherited from
`Component.getSnapshotBeforeUpdate`
***
### componentDidUpdate()?
> `optional` **componentDidUpdate**(`prevProps`, `prevState`, `snapshot`?): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](ErrorBoundary.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<`Props`> |
| `prevState` | `Readonly`<`State`> |
| `snapshot`? | `any` |
#### Returns
`void`
#### Inherited from
`Component.componentDidUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`Component.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`Component.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<`Props`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`Component.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<`Props`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`Component.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<`Props`> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`Component.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<`Props`> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`Component.UNSAFE_componentWillUpdate`
***
### getDerivedStateFromError()
> `static` **getDerivedStateFromError**(`error`): `State`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
#### Returns
`State`
***
### componentDidCatch()
> **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Overrides
`Component.componentDidCatch`
***
### handleRetry()
> `private` **handleRetry**(): `void`
#### Returns
`void`
***
### render()
> **render**(): `undefined` | `null` | `string` | `number` | `bigint` | `boolean` | `Iterable`<`ReactNode`, `any`, `any`> | `Promise`<`AwaitedReactNode`> | `Element`
#### Returns
`undefined` | `null` | `string` | `number` | `bigint` | `boolean` | `Iterable`<`ReactNode`, `any`, `any`> | `Promise`<`AwaitedReactNode`> | `Element`
#### Overrides
`Component.render`
---
---
url: /api/recharts/classes/Funnel.md
---
[@sqlrooms/recharts](../index.md) / Funnel
# Class: Funnel
## Extends
* `PureComponent`<[`FunnelProps`](../type-aliases/FunnelProps.md), `State`>
## Constructors
### new Funnel()
> **new Funnel**(`props`): [`Funnel`](Funnel.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`FunnelProps`](../type-aliases/FunnelProps.md) |
#### Returns
[`Funnel`](Funnel.md)
#### Inherited from
`PureComponent.constructor`
### new Funnel()
> **new Funnel**(`props`, `context`): [`Funnel`](Funnel.md)
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `props` | [`FunnelProps`](../type-aliases/FunnelProps.md) | |
| `context` | `any` | value of the parent [Context](https://react.dev/reference/react/Component#context) specified in `contextType`. |
#### Returns
[`Funnel`](Funnel.md)
#### Inherited from
`PureComponent.constructor`
## Properties
| Property | Modifier | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | - | `PureComponent.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | - | `PureComponent.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | - | `PureComponent.context` |
| `props` | `readonly` | `Readonly`<[`FunnelProps`](../type-aliases/FunnelProps.md)> | - | - | `PureComponent.props` |
| `displayName` | `static` | `string` | - | - | - |
| `defaultProps` | `static` | `object` | - | - | - |
| `defaultProps.stroke` | `public` | `string` | - | - | - |
| `defaultProps.fill` | `public` | `string` | - | - | - |
| `defaultProps.legendType` | `public` | `string` | - | - | - |
| `defaultProps.labelLine` | `public` | `boolean` | - | - | - |
| `defaultProps.hide` | `public` | `boolean` | - | - | - |
| `defaultProps.isAnimationActive` | `public` | `boolean` | - | - | - |
| `defaultProps.animationBegin` | `public` | `number` | - | - | - |
| `defaultProps.animationDuration` | `public` | `number` | - | - | - |
| `defaultProps.animationEasing` | `public` | `string` | - | - | - |
| `defaultProps.nameKey` | `public` | `string` | - | - | - |
| `defaultProps.lastShapeType` | `public` | `string` | - | - | - |
| `getRealFunnelData` | `static` | (`item`: [`Funnel`](Funnel.md)) => `any`\[] | - | - | - |
| `getRealWidthHeight` | `static` | (`item`: [`Funnel`](Funnel.md), `offset`: `ChartOffset`) => `object` | - | - | - |
| `getComposedData` | `static` | (`__namedParameters`: `object`) => `object` | - | - | - |
| `state` | `public` | `State` | - | `PureComponent.state` | - |
| `handleAnimationEnd` | `public` | () => `void` | - | - | - |
| `handleAnimationStart` | `public` | () => `void` | - | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* keyof `State` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | `State` | (`prevState`, `props`) => `null` | `State` | `Pick`<`State`, `K`> | `Pick`<`State`, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.forceUpdate`
***
### componentDidMount()?
> `optional` **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidMount`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`FunnelProps`](../type-aliases/FunnelProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`PureComponent.shouldComponentUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`PureComponent.componentWillUnmount`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](Funnel.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`FunnelProps`](../type-aliases/FunnelProps.md)> |
| `prevState` | `Readonly`<`State`> |
#### Returns
`any`
#### Inherited from
`PureComponent.getSnapshotBeforeUpdate`
***
### componentDidUpdate()?
> `optional` **componentDidUpdate**(`prevProps`, `prevState`, `snapshot`?): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](Funnel.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`FunnelProps`](../type-aliases/FunnelProps.md)> |
| `prevState` | `Readonly`<`State`> |
| `snapshot`? | `any` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`FunnelProps`](../type-aliases/FunnelProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`FunnelProps`](../type-aliases/FunnelProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`FunnelProps`](../type-aliases/FunnelProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`FunnelProps`](../type-aliases/FunnelProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillUpdate`
***
### getDerivedStateFromProps()
> `static` **getDerivedStateFromProps**(`nextProps`, `prevState`): `State`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | [`FunnelProps`](../type-aliases/FunnelProps.md) |
| `prevState` | `State` |
#### Returns
`State`
***
### isActiveIndex()
> **isActiveIndex**(`i`): `boolean`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `i` | `number` |
#### Returns
`boolean`
***
### renderTrapezoidsStatically()
> **renderTrapezoidsStatically**(`trapezoids`): `Element`\[]
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `trapezoids` | `FunnelTrapezoidItem`\[] |
#### Returns
`Element`\[]
***
### renderTrapezoidsWithAnimation()
> **renderTrapezoidsWithAnimation**(): `Element`
#### Returns
`Element`
***
### renderTrapezoids()
> **renderTrapezoids**(): `Element` | `Element`\[]
#### Returns
`Element` | `Element`\[]
***
### render()
> **render**(): `Element`
#### Returns
`Element`
#### Overrides
`PureComponent.render`
---
---
url: /api/recharts/classes/Legend.md
---
[@sqlrooms/recharts](../index.md) / Legend
# Class: Legend
## Extends
* `PureComponent`<[`LegendProps`](../type-aliases/LegendProps.md), `State`>
## Constructors
### new Legend()
> **new Legend**(`props`): [`Legend`](Legend.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`LegendProps`](../type-aliases/LegendProps.md) |
#### Returns
[`Legend`](Legend.md)
#### Inherited from
`PureComponent.constructor`
### new Legend()
> **new Legend**(`props`, `context`): [`Legend`](Legend.md)
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `props` | [`LegendProps`](../type-aliases/LegendProps.md) | |
| `context` | `any` | value of the parent [Context](https://react.dev/reference/react/Component#context) specified in `contextType`. |
#### Returns
[`Legend`](Legend.md)
#### Inherited from
`PureComponent.constructor`
## Properties
| Property | Modifier | Type | Description | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | `PureComponent.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | `PureComponent.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | `PureComponent.context` |
| `props` | `readonly` | `Readonly`<[`LegendProps`](../type-aliases/LegendProps.md)> | - | `PureComponent.props` |
| `state` | `public` | `Readonly`<`State`> | - | `PureComponent.state` |
| `displayName` | `static` | `string` | - | - |
| `defaultProps` | `static` | `object` | - | - |
| `defaultProps.iconSize` | `public` | `number` | - | - |
| `defaultProps.layout` | `public` | `string` | - | - |
| `defaultProps.align` | `public` | `string` | - | - |
| `defaultProps.verticalAlign` | `public` | `string` | - | - |
| `wrapperNode` | `private` | `any` | - | - |
| `lastBoundingBox` | `public` | `object` | - | - |
| `lastBoundingBox.width` | `public` | `number` | - | - |
| `lastBoundingBox.height` | `public` | `number` | - | - |
| `updateBBox` | `private` | `any` | - | - |
| `getBBoxSnapshot` | `private` | `any` | - | - |
| `getDefaultPosition` | `private` | `any` | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* keyof `State` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | `State` | (`prevState`, `props`) => `null` | `State` | `Pick`<`State`, `K`> | `Pick`<`State`, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.forceUpdate`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`LegendProps`](../type-aliases/LegendProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`PureComponent.shouldComponentUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`PureComponent.componentWillUnmount`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](Legend.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`LegendProps`](../type-aliases/LegendProps.md)> |
| `prevState` | `Readonly`<`State`> |
#### Returns
`any`
#### Inherited from
`PureComponent.getSnapshotBeforeUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`LegendProps`](../type-aliases/LegendProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`LegendProps`](../type-aliases/LegendProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`LegendProps`](../type-aliases/LegendProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`LegendProps`](../type-aliases/LegendProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillUpdate`
***
### getWithHeight()
> `static` **getWithHeight**(`item`, `chartWidth`): `null` | { `height`: `number`; } | { `width`: `number`; }
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `item` | { `props`: { `layout`: `LayoutType`; `height`: `number`; `width`: `number`; }; } |
| `item.props` | { `layout`: `LayoutType`; `height`: `number`; `width`: `number`; } |
| `item.props.layout`? | `LayoutType` |
| `item.props.height`? | `number` |
| `item.props.width`? | `number` |
| `chartWidth` | `number` |
#### Returns
`null` | { `height`: `number`; } | { `width`: `number`; }
***
### componentDidMount()
> **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Overrides
`PureComponent.componentDidMount`
***
### componentDidUpdate()
> **componentDidUpdate**(): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](Legend.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Returns
`void`
#### Overrides
`PureComponent.componentDidUpdate`
***
### getBBox()
> **getBBox**(): `DOMRect`
#### Returns
`DOMRect`
***
### render()
> **render**(): `Element`
#### Returns
`Element`
#### Overrides
`PureComponent.render`
---
---
url: /api/recharts/classes/Line.md
---
[@sqlrooms/recharts](../index.md) / Line
# Class: Line
## Extends
* `PureComponent`<[`LineProps`](../type-aliases/LineProps.md), `State`>
## Constructors
### new Line()
> **new Line**(`props`): [`Line`](Line.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`LineProps`](../type-aliases/LineProps.md) |
#### Returns
[`Line`](Line.md)
#### Inherited from
`PureComponent.constructor`
### new Line()
> **new Line**(`props`, `context`): [`Line`](Line.md)
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `props` | [`LineProps`](../type-aliases/LineProps.md) | |
| `context` | `any` | value of the parent [Context](https://react.dev/reference/react/Component#context) specified in `contextType`. |
#### Returns
[`Line`](Line.md)
#### Inherited from
`PureComponent.constructor`
## Properties
| Property | Modifier | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | - | `PureComponent.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | - | `PureComponent.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | - | `PureComponent.context` |
| `props` | `readonly` | `Readonly`<[`LineProps`](../type-aliases/LineProps.md)> | - | - | `PureComponent.props` |
| `displayName` | `static` | `string` | - | - | - |
| `defaultProps` | `static` | `object` | - | - | - |
| `defaultProps.xAxisId` | `public` | `number` | - | - | - |
| `defaultProps.yAxisId` | `public` | `number` | - | - | - |
| `defaultProps.connectNulls` | `public` | `boolean` | - | - | - |
| `defaultProps.activeDot` | `public` | `boolean` | - | - | - |
| `defaultProps.dot` | `public` | `boolean` | - | - | - |
| `defaultProps.legendType` | `public` | `string` | - | - | - |
| `defaultProps.stroke` | `public` | `string` | - | - | - |
| `defaultProps.strokeWidth` | `public` | `number` | - | - | - |
| `defaultProps.fill` | `public` | `string` | - | - | - |
| `defaultProps.points` | `public` | `LinePointItem`\[] | - | - | - |
| `defaultProps.isAnimationActive` | `public` | `boolean` | - | - | - |
| `defaultProps.animateNewValues` | `public` | `boolean` | - | - | - |
| `defaultProps.animationBegin` | `public` | `number` | - | - | - |
| `defaultProps.animationDuration` | `public` | `number` | - | - | - |
| `defaultProps.animationEasing` | `public` | `string` | - | - | - |
| `defaultProps.hide` | `public` | `boolean` | - | - | - |
| `defaultProps.label` | `public` | `boolean` | - | - | - |
| `getComposedData` | `static` | (`__namedParameters`: `object`) => `object` | Compose the data of each group | - | - |
| `mainCurve?` | `public` | `SVGPathElement` | - | - | - |
| `state` | `public` | `State` | - | `PureComponent.state` | - |
| `generateSimpleStrokeDasharray` | `public` | (`totalLength`: `number`, `length`: `number`) => `string` | - | - | - |
| `getStrokeDasharray` | `public` | (`length`: `number`, `totalLength`: `number`, `lines`: `number`\[]) => `string` | - | - | - |
| `id` | `public` | `string` | - | - | - |
| `pathRef` | `public` | (`node`: `SVGPathElement`) => `void` | - | - | - |
| `handleAnimationEnd` | `public` | () => `void` | - | - | - |
| `handleAnimationStart` | `public` | () => `void` | - | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* keyof `State` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | `State` | (`prevState`, `props`) => `null` | `State` | `Pick`<`State`, `K`> | `Pick`<`State`, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.forceUpdate`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`LineProps`](../type-aliases/LineProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`PureComponent.shouldComponentUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`PureComponent.componentWillUnmount`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](Line.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`LineProps`](../type-aliases/LineProps.md)> |
| `prevState` | `Readonly`<`State`> |
#### Returns
`any`
#### Inherited from
`PureComponent.getSnapshotBeforeUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`LineProps`](../type-aliases/LineProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`LineProps`](../type-aliases/LineProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`LineProps`](../type-aliases/LineProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`LineProps`](../type-aliases/LineProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillUpdate`
***
### componentDidMount()
> **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Overrides
`PureComponent.componentDidMount`
***
### componentDidUpdate()
> **componentDidUpdate**(): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](Line.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Returns
`void`
#### Overrides
`PureComponent.componentDidUpdate`
***
### getDerivedStateFromProps()
> `static` **getDerivedStateFromProps**(`nextProps`, `prevState`): `State`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | [`LineProps`](../type-aliases/LineProps.md) |
| `prevState` | `State` |
#### Returns
`State`
***
### getTotalLength()
> **getTotalLength**(): `number`
#### Returns
`number`
***
### repeat()
> `static` **repeat**(`lines`, `count`): `number`\[]
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `lines` | `number`\[] |
| `count` | `number` |
#### Returns
`number`\[]
***
### renderErrorBar()
> **renderErrorBar**(`needClip`, `clipPathId`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `needClip` | `boolean` |
| `clipPathId` | `string` |
#### Returns
`Element`
***
### renderDotItem()
> `static` **renderDotItem**(`option`, `props`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `option` | `LineDot` |
| `props` | `any` |
#### Returns
`Element`
***
### renderDots()
> **renderDots**(`needClip`, `clipDot`, `clipPathId`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `needClip` | `boolean` |
| `clipDot` | `boolean` |
| `clipPathId` | `string` |
#### Returns
`Element`
***
### renderCurveStatically()
> **renderCurveStatically**(`points`, `needClip`, `clipPathId`, `props`?): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `points` | `LinePointItem`\[] |
| `needClip` | `boolean` |
| `clipPathId` | `string` |
| `props`? | { `strokeDasharray`: `string`; } |
| `props.strokeDasharray`? | `string` |
#### Returns
`Element`
***
### renderCurveWithAnimation()
> **renderCurveWithAnimation**(`needClip`, `clipPathId`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `needClip` | `boolean` |
| `clipPathId` | `string` |
#### Returns
`Element`
***
### renderCurve()
> **renderCurve**(`needClip`, `clipPathId`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `needClip` | `boolean` |
| `clipPathId` | `string` |
#### Returns
`Element`
***
### render()
> **render**(): `Element`
#### Returns
`Element`
#### Overrides
`PureComponent.render`
---
---
url: /api/recharts/classes/Pie.md
---
[@sqlrooms/recharts](../index.md) / Pie
# Class: Pie
## Extends
* `PureComponent`<[`PieProps`](../type-aliases/PieProps.md), `State`>
## Constructors
### new Pie()
> **new Pie**(`props`): [`Pie`](Pie.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`PieProps`](../type-aliases/PieProps.md) |
#### Returns
[`Pie`](Pie.md)
#### Overrides
`PureComponent.constructor`
## Properties
| Property | Modifier | Type | Description | Overrides | Inherited from |
| ------ | ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | - | `PureComponent.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | - | `PureComponent.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | - | `PureComponent.context` |
| `props` | `readonly` | `Readonly`<[`PieProps`](../type-aliases/PieProps.md)> | - | - | `PureComponent.props` |
| `pieRef` | `public` | `SVGGElement` | - | - | - |
| `sectorRefs` | `public` | `SVGGElement`\[] | - | - | - |
| `displayName` | `static` | `string` | - | - | - |
| `defaultProps` | `static` | `object` | - | - | - |
| `defaultProps.stroke` | `public` | `string` | - | - | - |
| `defaultProps.fill` | `public` | `string` | - | - | - |
| `defaultProps.legendType` | `public` | `string` | - | - | - |
| `defaultProps.cx` | `public` | `string` | - | - | - |
| `defaultProps.cy` | `public` | `string` | - | - | - |
| `defaultProps.startAngle` | `public` | `number` | - | - | - |
| `defaultProps.endAngle` | `public` | `number` | - | - | - |
| `defaultProps.innerRadius` | `public` | `number` | - | - | - |
| `defaultProps.outerRadius` | `public` | `string` | - | - | - |
| `defaultProps.paddingAngle` | `public` | `number` | - | - | - |
| `defaultProps.labelLine` | `public` | `boolean` | - | - | - |
| `defaultProps.hide` | `public` | `boolean` | - | - | - |
| `defaultProps.minAngle` | `public` | `number` | - | - | - |
| `defaultProps.isAnimationActive` | `public` | `boolean` | - | - | - |
| `defaultProps.animationBegin` | `public` | `number` | - | - | - |
| `defaultProps.animationDuration` | `public` | `number` | - | - | - |
| `defaultProps.animationEasing` | `public` | `string` | - | - | - |
| `defaultProps.nameKey` | `public` | `string` | - | - | - |
| `defaultProps.blendStroke` | `public` | `boolean` | - | - | - |
| `defaultProps.rootTabIndex` | `public` | `number` | - | - | - |
| `parseDeltaAngle` | `static` | (`startAngle`: `number`, `endAngle`: `number`) => `number` | - | - | - |
| `getRealPieData` | `static` | (`itemProps`: [`PieProps`](../type-aliases/PieProps.md)) => `any`\[] | - | - | - |
| `parseCoordinateOfPie` | `static` | (`itemProps`: [`PieProps`](../type-aliases/PieProps.md), `offset`: `ChartOffset`) => `object` | - | - | - |
| `getComposedData` | `static` | (`__namedParameters`: `object`) => `Omit`<[`PieProps`](../type-aliases/PieProps.md), `"dataKey"`> | - | - | - |
| `state` | `public` | `State` | - | `PureComponent.state` | - |
| `id` | `public` | `string` | - | - | - |
| `handleAnimationEnd` | `public` | () => `void` | - | - | - |
| `handleAnimationStart` | `public` | () => `void` | - | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* keyof `State` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | `State` | (`prevState`, `props`) => `null` | `State` | `Pick`<`State`, `K`> | `Pick`<`State`, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.forceUpdate`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`PieProps`](../type-aliases/PieProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`PureComponent.shouldComponentUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`PureComponent.componentWillUnmount`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](Pie.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`PieProps`](../type-aliases/PieProps.md)> |
| `prevState` | `Readonly`<`State`> |
#### Returns
`any`
#### Inherited from
`PureComponent.getSnapshotBeforeUpdate`
***
### componentDidUpdate()?
> `optional` **componentDidUpdate**(`prevProps`, `prevState`, `snapshot`?): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](Pie.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`PieProps`](../type-aliases/PieProps.md)> |
| `prevState` | `Readonly`<`State`> |
| `snapshot`? | `any` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`PieProps`](../type-aliases/PieProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillReceiveProps`
***
### ~~UNSAFE\_componentWillReceiveProps()?~~
> `optional` **UNSAFE\_componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`PieProps`](../type-aliases/PieProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillReceiveProps`
***
### ~~componentWillUpdate()?~~
> `optional` **componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`PieProps`](../type-aliases/PieProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillUpdate`
***
### ~~UNSAFE\_componentWillUpdate()?~~
> `optional` **UNSAFE\_componentWillUpdate**(`nextProps`, `nextState`, `nextContext`): `void`
Called immediately before rendering when new props or state is received. Not called for the initial render.
Note: You cannot call Component.setState here.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`PieProps`](../type-aliases/PieProps.md)> |
| `nextState` | `Readonly`<`State`> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use getSnapshotBeforeUpdate instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillUpdate`
***
### getDerivedStateFromProps()
> `static` **getDerivedStateFromProps**(`nextProps`, `prevState`): `State`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | [`PieProps`](../type-aliases/PieProps.md) |
| `prevState` | `State` |
#### Returns
`State`
***
### getTextAnchor()
> `static` **getTextAnchor**(`x`, `cx`): `"end"` | `"middle"` | `"start"`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `x` | `number` |
| `cx` | `number` |
#### Returns
`"end"` | `"middle"` | `"start"`
***
### isActiveIndex()
> **isActiveIndex**(`i`): `boolean`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `i` | `number` |
#### Returns
`boolean`
***
### hasActiveIndex()
> **hasActiveIndex**(): `number` | `boolean`
#### Returns
`number` | `boolean`
***
### renderLabelLineItem()
> `static` **renderLabelLineItem**(`option`, `props`, `key`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `option` | `PieLabelLine` |
| `props` | `any` |
| `key` | `string` |
#### Returns
`Element`
***
### renderLabelItem()
> `static` **renderLabelItem**(`option`, `props`, `value`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `option` | [`PieLabel`](../type-aliases/PieLabel.md) |
| `props` | `any` |
| `value` | `any` |
#### Returns
`Element`
***
### renderLabels()
> **renderLabels**(`sectors`): `Element`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `sectors` | `PieSectorDataItem`\[] |
#### Returns
`Element`
***
### renderSectorsStatically()
> **renderSectorsStatically**(`sectors`): `Element`\[]
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `sectors` | `PieSectorDataItem`\[] |
#### Returns
`Element`\[]
***
### renderSectorsWithAnimation()
> **renderSectorsWithAnimation**(): `Element`
#### Returns
`Element`
***
### attachKeyboardHandlers()
> **attachKeyboardHandlers**(`pieRef`): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `pieRef` | `SVGGElement` |
#### Returns
`void`
***
### renderSectors()
> **renderSectors**(): `Element` | `Element`\[]
#### Returns
`Element` | `Element`\[]
***
### componentDidMount()
> **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Overrides
`PureComponent.componentDidMount`
***
### render()
> **render**(): `Element`
#### Returns
`Element`
#### Overrides
`PureComponent.render`
---
---
url: /api/recharts/classes/PolarAngleAxis.md
---
[@sqlrooms/recharts](../index.md) / PolarAngleAxis
# Class: PolarAngleAxis
## Extends
* `PureComponent`<[`PolarAngleAxisProps`](../type-aliases/PolarAngleAxisProps.md)>
## Constructors
### new PolarAngleAxis()
> **new PolarAngleAxis**(`props`): [`PolarAngleAxis`](PolarAngleAxis.md)
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `props` | [`PolarAngleAxisProps`](../type-aliases/PolarAngleAxisProps.md) |
#### Returns
[`PolarAngleAxis`](PolarAngleAxis.md)
#### Inherited from
`PureComponent.constructor`
### new PolarAngleAxis()
> **new PolarAngleAxis**(`props`, `context`): [`PolarAngleAxis`](PolarAngleAxis.md)
#### Parameters
| Parameter | Type | Description |
| ------ | ------ | ------ |
| `props` | [`PolarAngleAxisProps`](../type-aliases/PolarAngleAxisProps.md) | |
| `context` | `any` | value of the parent [Context](https://react.dev/reference/react/Component#context) specified in `contextType`. |
#### Returns
[`PolarAngleAxis`](PolarAngleAxis.md)
#### Inherited from
`PureComponent.constructor`
## Properties
| Property | Modifier | Type | Description | Inherited from |
| ------ | ------ | ------ | ------ | ------ |
| `contextType?` | `static` | `Context`<`any`> | If set, `this.context` will be set at runtime to the current value of the given Context. **Example** `type MyContext = number const Ctx = React.createContext(0) class Foo extends React.Component { static contextType = Ctx context!: React.ContextType render () { return <>My context's value: {this.context}>; } }` **See** | `PureComponent.contextType` |
| ~~`propTypes?`~~ | `static` | `any` | Ignored by React. **Deprecated** Only kept in types for backwards compatibility. Will be removed in a future major release. | `PureComponent.propTypes` |
| `context` | `public` | `unknown` | If using React Context, re-declare this in your class to be the `React.ContextType` of your `static contextType`. Should be used with type annotation or static contextType. **Example** `static contextType = MyContext // For TS pre-3.7: context!: React.ContextType // For TS 3.7 and above: declare context: React.ContextType` **See** [React Docs](https://react.dev/reference/react/Component#context) | `PureComponent.context` |
| `props` | `readonly` | `Readonly`<[`PolarAngleAxisProps`](../type-aliases/PolarAngleAxisProps.md)> | - | `PureComponent.props` |
| `state` | `public` | `Readonly`<{}> | - | `PureComponent.state` |
| `displayName` | `static` | `string` | - | - |
| `axisType` | `static` | `string` | - | - |
| `defaultProps` | `static` | `object` | - | - |
| `defaultProps.type` | `public` | `string` | - | - |
| `defaultProps.angleAxisId` | `public` | `number` | - | - |
| `defaultProps.scale` | `public` | `string` | - | - |
| `defaultProps.cx` | `public` | `number` | - | - |
| `defaultProps.cy` | `public` | `number` | - | - |
| `defaultProps.orientation` | `public` | `string` | - | - |
| `defaultProps.axisLine` | `public` | `boolean` | - | - |
| `defaultProps.tickLine` | `public` | `boolean` | - | - |
| `defaultProps.tickSize` | `public` | `number` | - | - |
| `defaultProps.tick` | `public` | `boolean` | - | - |
| `defaultProps.hide` | `public` | `boolean` | - | - |
| `defaultProps.allowDuplicatedCategory` | `public` | `boolean` | - | - |
## Methods
### setState()
> **setState**<`K`>(`state`, `callback`?): `void`
#### Type Parameters
| Type Parameter |
| ------ |
| `K` *extends* `never` |
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `state` | `null` | {} | (`prevState`, `props`) => `null` | {} | `Pick`<{}, `K`> | `Pick`<{}, `K`> |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.setState`
***
### forceUpdate()
> **forceUpdate**(`callback`?): `void`
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `callback`? | () => `void` |
#### Returns
`void`
#### Inherited from
`PureComponent.forceUpdate`
***
### componentDidMount()?
> `optional` **componentDidMount**(): `void`
Called immediately after a component is mounted. Setting state here will trigger re-rendering.
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidMount`
***
### shouldComponentUpdate()?
> `optional` **shouldComponentUpdate**(`nextProps`, `nextState`, `nextContext`): `boolean`
Called to determine whether the change in props and state should trigger a re-render.
`Component` always returns true.
`PureComponent` implements a shallow comparison on props and state and returns true if any
props or states have changed.
If false is returned, Component.render, `componentWillUpdate`
and `componentDidUpdate` will not be called.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`PolarAngleAxisProps`](../type-aliases/PolarAngleAxisProps.md)> |
| `nextState` | `Readonly`<{}> |
| `nextContext` | `any` |
#### Returns
`boolean`
#### Inherited from
`PureComponent.shouldComponentUpdate`
***
### componentWillUnmount()?
> `optional` **componentWillUnmount**(): `void`
Called immediately before a component is destroyed. Perform any necessary cleanup in this method, such as
cancelled network requests, or cleaning up any DOM elements created in `componentDidMount`.
#### Returns
`void`
#### Inherited from
`PureComponent.componentWillUnmount`
***
### componentDidCatch()?
> `optional` **componentDidCatch**(`error`, `errorInfo`): `void`
Catches exceptions generated in descendant components. Unhandled exceptions will cause
the entire component tree to unmount.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `error` | `Error` |
| `errorInfo` | `ErrorInfo` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidCatch`
***
### getSnapshotBeforeUpdate()?
> `optional` **getSnapshotBeforeUpdate**(`prevProps`, `prevState`): `any`
Runs before React applies the result of Component.render render to the document, and
returns an object to be given to [componentDidUpdate](PolarAngleAxis.md#componentdidupdate). Useful for saving
things such as scroll position before Component.render render causes changes to it.
Note: the presence of this method prevents any of the deprecated
lifecycle events from running.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`PolarAngleAxisProps`](../type-aliases/PolarAngleAxisProps.md)> |
| `prevState` | `Readonly`<{}> |
#### Returns
`any`
#### Inherited from
`PureComponent.getSnapshotBeforeUpdate`
***
### componentDidUpdate()?
> `optional` **componentDidUpdate**(`prevProps`, `prevState`, `snapshot`?): `void`
Called immediately after updating occurs. Not called for the initial render.
The snapshot is only present if [getSnapshotBeforeUpdate](PolarAngleAxis.md#getsnapshotbeforeupdate) is present and returns non-null.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `prevProps` | `Readonly`<[`PolarAngleAxisProps`](../type-aliases/PolarAngleAxisProps.md)> |
| `prevState` | `Readonly`<{}> |
| `snapshot`? | `any` |
#### Returns
`void`
#### Inherited from
`PureComponent.componentDidUpdate`
***
### ~~componentWillMount()?~~
> `optional` **componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead; will stop working in React 17
#### See
*
*
#### Inherited from
`PureComponent.componentWillMount`
***
### ~~UNSAFE\_componentWillMount()?~~
> `optional` **UNSAFE\_componentWillMount**(): `void`
Called immediately before mounting occurs, and before Component.render.
Avoid introducing any side-effects or subscriptions in this method.
This method will not stop working in React 17.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Returns
`void`
#### Deprecated
16.3, use ComponentLifecycle.componentDidMount componentDidMount or the constructor instead
#### See
*
*
#### Inherited from
`PureComponent.UNSAFE_componentWillMount`
***
### ~~componentWillReceiveProps()?~~
> `optional` **componentWillReceiveProps**(`nextProps`, `nextContext`): `void`
Called when the component may be receiving new props.
React may call this even if props have not changed, so be sure to compare new and existing
props if you only want to handle changes.
Calling Component.setState generally does not trigger this method.
Note: the presence of NewLifecycle.getSnapshotBeforeUpdate getSnapshotBeforeUpdate
or StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps prevents
this from being invoked.
#### Parameters
| Parameter | Type |
| ------ | ------ |
| `nextProps` | `Readonly`<[`PolarAngleAxisProps`](../type-aliases/PolarAngleAxisProps.md)> |
| `nextContext` | `any` |
#### Returns
`void`
#### Deprecated
16.3, use static StaticLifecycle.getDerivedStateFromProps getDerivedStateFromProps instead; will stop working in React 17
#### See
*