### Scaffold Nube App with npm, Yarn, pnpm, Bun
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Commands to create a new Nube App using different package managers. This process downloads and runs the create-nube-app CLI to guide you through project setup.
```bash
npm create nube-app@latest
```
```bash
yarn create nube-app
```
```bash
pnpm create nube-app
```
```bash
bun create nube-app
```
--------------------------------
### Example Development Mode Response
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
An example of the expected output when the development mode is active and the verification command is executed. It shows the structure of the application's state within the NubeSDK.
```json
{
"1028": {
"id": "1028",
"script": "http://localhost:8080/main.min.js",
"registered": true
}
}
```
--------------------------------
### Tsup Configuration for Nube SDK Projects
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Example tsup configuration file (tsup.config.js) for building Nube SDK projects. It specifies entry points, formats, target, minification, and JSX aliasing.
```javascript
//tsup.config.js
import { defineConfig } from "tsup";
export default defineConfig({
entry: ["src/main.tsx"],
format: ["esm"],
target: "esnext",
clean: true,
minify: true,
bundle: true,
sourcemap: false,
splitting: false,
skipNodeModulesBundle: false,
esbuildOptions(options) { // ONLY IF YOU USE JSX
options.alias = {
"@tiendanube/nube-sdk-jsx/dist/jsx-runtime": "@tiendanube/nube-sdk-jsx/jsx-runtime",
};
},
outExtension: ({ options }) => ({
js: options.minify ? ".min.js" : ".js"
})
});
```
--------------------------------
### Install Tsup for Building with npm, Yarn, pnpm, Bun
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Installs tsup as a development dependency, a tool recommended for building Nube SDK projects, as it comes pre-configured in official templates.
```bash
npm install -D tsup
```
```bash
yarn add -D tsup
```
```bash
pnpm add -D tsup
```
```bash
bun add -D tsup
```
--------------------------------
### Install Nube SDK UI Package with npm, Yarn, pnpm, Bun
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Installs the @tiendanube/nube-sdk-ui package, which is necessary for developing applications with a user interface.
```bash
npm install @tiendanube/nube-sdk-ui
```
```bash
yarn add @tiendanube/nube-sdk-ui
```
```bash
pnpm add @tiendanube/nube-sdk-ui
```
```bash
bun add @tiendanube/nube-sdk-ui
```
--------------------------------
### Install Nube SDK JSX Package with npm, Yarn, pnpm, Bun
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Installs the @tiendanube/nube-sdk-jsx package for projects that utilize JSX/TSX syntax.
```bash
npm install @tiendanube/nube-sdk-jsx
```
```bash
yarn add @tiendanube/nube-sdk-jsx
```
```bash
pnpm add @tiendanube/nube-sdk-jsx
```
```bash
bun add @tiendanube/nube-sdk-jsx
```
--------------------------------
### Start Development Server (Bun)
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Starts the local development server using Bun. Bun is a fast all-in-one JavaScript runtime, bundler, transpiler, and package manager.
```bash
bun run dev
```
--------------------------------
### Start Development Server (npm)
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Starts the local development server using npm. This command is typically used after creating an application with the create-nube-app CLI.
```bash
npm run dev
```
--------------------------------
### Nube App Entrypoint Example (main.ts)
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
An example of a main entry point file for a Nube App using TypeScript. It imports the NubeSDK type and exports an async function to initialize the app.
```typescript
// main.ts
import type { NubeSDK } from "@tiendanube/nube-sdk-types";
export async function App(nube: NubeSDK) {
// your code
}
```
--------------------------------
### Install Nube SDK Types with npm, Yarn, pnpm, Bun
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Installs TypeScript and the @tiendanube/nube-sdk-types package as development dependencies. This is required for accessing all Nube SDK functionalities.
```bash
npm install -D typescript @tiendanube/nube-sdk-types
```
```bash
yarn add -D typescript @tiendanube/nube-sdk-types
```
```bash
pnpm add -D typescript @tiendanube/nube-sdk-types
```
```bash
bun add -D typescript @tiendanube/nube-sdk-types
```
--------------------------------
### Start Development Server (Yarn)
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Starts the local development server using Yarn. This command is an alternative to npm for managing project dependencies and running scripts.
```bash
yarn dev
```
--------------------------------
### Start Development Server (pnpm)
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Starts the local development server using pnpm. pnpm is a performant package manager that enforces a strict node_modules structure.
```bash
pnpm run dev
```
--------------------------------
### Build Script with npm, Yarn, pnpm, Bun
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Commands to execute the build process for your Nube application script using various package managers. This step is crucial before adding your script to the application.
```bash
npm run build
```
```bash
yarn build
```
```bash
pnpm run build
```
```bash
bun run build
```
--------------------------------
### TypeScript Compiler Options for Nube SDK
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Recommended TypeScript compiler options for Nube SDK projects. Includes settings for target, JSX, module resolution, and strictness.
```json
{
"compilerOptions": {
"target": "esnext",
"jsx": "react-jsx",
"jsxImportSource": "@tiendanube/nube-sdk-jsx/dist", // ONLY IF YOU USE JSX
"module": "commonjs",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true
}
}
```
--------------------------------
### Verify Development Mode Configuration
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/getting-started
Executes a command in the browser console to verify if the development mode is active and correctly configured. It checks the NubeSDK state for application details.
```javascript
nubeSDK.getState().apps;
```
--------------------------------
### Access Available Theme Tokens
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Provides examples of accessing various theme tokens for colors, borders, and component-specific styling properties from the `theme` object.
```javascript
import { theme } from "@tiendanube/nube-sdk-ui";
// Colors
theme.color.accent // Primary accent color
theme.color.main.foreground // Main text color
theme.color.main.background // Main background color
// Borders
theme.border.color // Default border color
theme.border.radius // Default border radius
// Component-specific tokens
theme.button.foreground // Button text color
theme.button.background // Button background color
theme.button.borderColor // Button border color
theme.button.borderRadius // Button border radius
theme.input.border.color // Input border color
theme.header.foreground // Header text color
theme.header.background // Header background color
theme.header.logo.maxWidth // Header logo max width
theme.header.logo.fontSize // Header logo font size
theme.footer.foreground // Footer text color
theme.footer.background // Footer background color
theme.heading.font // Heading font family
theme.heading.fontWeight // Heading font weight
```
--------------------------------
### Complete Component with Multiple Styling Approaches
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Provides a comprehensive example of a React component that utilizes both `StyleSheet.create` for reusable styles and `styled()` for dynamic styling, demonstrating a complete integration of NubeSDK UI styling features.
```jsx
import { styled, StyleSheet, theme } from "@tiendanube/nube-sdk-ui";
import { Box, Button, Text } from "@tiendanube/nube-sdk-jsx";
// Reusable styles
const styles = StyleSheet.create({
container: {
backgroundColor: theme.color.main.background,
borderRadius: theme.border.radius,
padding: "24px",
},
title: {
color: theme.color.main.foreground,
fontSize: "24px",
fontWeight: "bold",
marginBottom: "16px",
},
});
// Static styled component
const StyledButton = styled(Button)`
background-color: ${theme.color.accent};
color: white;
padding: 12px 24px;
border-radius: ${theme.border.radius};
border: 1px solid ${theme.border.color};
transition: all 0.2s;
&:hover {
transform: translateY(-2px);
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
`;
// Usage
Welcome to NubeSDKGet Started
```
--------------------------------
### Accordion Usage Example
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/components/accordion
Demonstrates how to use the Accordion component with its subcomponents. It shows how to set a default expanded item and apply custom styles.
```jsx
import { Accordion } from "@tiendanube/nube-sdk-jsx";
Accordion Item 1Accordion Content 1Accordion Item 2Accordion Content 2;
```
--------------------------------
### Display Image with Nuvemshop SDK JSX
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/components/image
This example demonstrates how to use the Image component from the Nuvemshop SDK JSX to display a basic image. It requires the 'src' and 'alt' properties for the image source and accessibility.
```jsx
import { Image } from "@tiendanube/nube-sdk-jsx";
function MyComponent() {
return (
);
}
```
--------------------------------
### Render Toast Component in UI Slot
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/components/toast
This example demonstrates how to import and use the Toast component from '@tiendanube/nube-sdk-jsx'. It shows how to create a Toast with a title and description, and then send it to a specific UI slot (corner_bottom_right) using the NubeSDK.
```JavaScript
import type { NubeSDK } from "@tiendanube/nube-sdk-types";
import { Toast } from "@tiendanube/nube-sdk-jsx";
const ToastComponent = () => (
Success!
Your changes have been saved.
);
export function App(nube: NubeSDK) {
nube.send("ui:slot:set", () => ({
ui: {
slots: {
corner_bottom_right: ,
},
},
}));
}
```
--------------------------------
### Configuring Cart Validation - TypeScript
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/script-structure
Demonstrates how to configure the script's behavior by dispatching the 'config:set' event. This example enables cart content validation.
```TypeScript
import type { NubeSDK } from "@tiendanube/nube-sdk-types";
export function App(nube: NubeSDK) {
// Tell NubeSDK that this script wants to validate the content of the cart
nube.send("config:set", () => ({
config: {
has_cart_validation: true
},
}));
}
```
--------------------------------
### Render Text with Color and Background
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/components/text
Demonstrates how to use the Text component to display text with specified color and background styles. This example utilizes the '@tiendanube/nube-sdk-jsx' library.
```jsx
import { Box, Text } from "@tiendanube/nube-sdk-jsx";
function MyComponent() {
return (
Hello!!
);
}
```
--------------------------------
### Render and Clear Components in Slots using NubeSDK
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/components
Demonstrates how to render UI components into specific slots within the application and how to clear them. This is achieved using the `nube.render()` and `nube.clearSlot()` methods, respectively. The example uses the `Text` component from the `@tiendanube/nube-sdk` library.
```javascript
import { Text } from "@tiendanube/nube-sdk";
// Render a component into a slot
nube.render("after_address_form", Hello World);
// Clear a component from a slot
nube.clearSlot("after_address_form");
```
--------------------------------
### Styled Component with Complex Animations
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Provides an example of creating a styled component with complex animations using multiple keyframes. It defines 'bounce' and 'fadeInUp' animations and applies them conditionally on hover.
```javascript
const bounce = keyframes`
0%, 20%, 53%, 80%, 100% {
transform: translate3d(0, 0, 0);
}
40%, 43% {
transform: translate3d(0, -30px, 0);
}
70% {
transform: translate3d(0, -15px, 0);
}
90% {
transform: translate3d(0, -4px, 0);
}
`;
const fadeInUp = keyframes`
0% {
opacity: 0;
transform: translate3d(0, 40px, 0);
}
100% {
opacity: 1;
transform: translate3d(0, 0, 0);
}
`;
const AnimatedComponent = styled(box)`
animation: ${bounce} 1s ease-in-out infinite;
&:hover {
animation: ${fadeInUp} 0.6s ease-out;
}
`;
```
--------------------------------
### Display Image with Responsive Sources in Nuvemshop SDK JSX
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/components/image
This example shows how to configure the Image component with responsive sources using media queries. The 'sources' property accepts an array of ImageSource objects, each with a 'src' and an optional 'media' query to adapt the image based on screen size.
```jsx
export function Logo() {
return (
);
}
```
--------------------------------
### Get Browser APIs with Nuvemshop SDK
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/script-structure
Demonstrates how to retrieve browser-specific APIs using the `getBrowserAPIs()` method provided by the Nuvemshop SDK. These APIs enable interactions with the browser environment, including making HTTP requests and accessing `localStorage`.
```typescript
import type { NubeSDK } from "@tiendanube/nube-sdk-types";
export function App(nube: NubeSDK) {
// Get browser APIs
const browser = nube.getBrowserAPIs();
// Use browser APIs for various operations
// Example: Making HTTP requests, accessing localStorage, etc.
}
```
--------------------------------
### Rendering Static and Dynamic Components - TypeScript
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/script-structure
Illustrates how to use the 'render' method to display components in UI slots. It shows rendering a static 'Hello World' text and a dynamic component that displays the number of items in the cart.
```TypeScript
import type { NubeSDK } from "@tiendanube/nube-sdk-types";
import { Text } from "@tiendanube/nube-sdk";
export function App(nube: NubeSDK) {
// Render a static component
nube.render("after_address_form", Hello World);
// Render a dynamic component based on state
nube.render("after_contact_form", (state) => {
const cartItems = state.cart.items.length;
return (
You have {cartItems} items in your cart
);
});
}
```
--------------------------------
### Responsive Design with Media Queries
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Shows how to implement responsive layouts using media queries within styled components to adapt styles based on screen size.
```javascript
const ResponsiveContainer = styled(box)`
padding: 16px;
flex-direction: column;
@media (min-width: 768px) {
padding: 24px;
flex-direction: row;
}
`;
```
--------------------------------
### Configure Script Initialization
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/events
This snippet shows how to use the `config:set` event, dispatched by `script`, to set initial configuration for the script. This includes enabling features like cart validation.
```javascript
nube.send("config:set", () => ({
config: {
has_cart_validation: true
},
}));
```
--------------------------------
### Responsive Box with Media Queries
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Illustrates how to apply responsive styles to a Box component using media queries within the `styled()` function. It changes padding and background color based on screen width.
```javascript
const ResponsiveBox = styled(Box)`
background-color: red;
padding: 16px;
@media (max-width: 768px) {
padding: 8px;
background-color: blue;
}
@media (min-width: 1024px) {
padding: 24px;
background-color: green;
}
`;
```
--------------------------------
### Create Reusable Styles with StyleSheet.create (UI SDK)
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Demonstrates using `StyleSheet.create` with components from the UI SDK for creating type-safe styles. Requires `@tiendanube/nube-sdk-ui`.
```javascript
import { StyleSheet } from "@tiendanube/nube-sdk-ui";
import { box, button } from "@tiendanube/nube-sdk-ui";
const styles = StyleSheet.create({
container: {
backgroundColor: "red",
padding: "16px",
borderRadius: "8px",
},
button: {
backgroundColor: "blue",
color: "white",
padding: "12px 24px",
},
});
box({
style: styles.container,
children: [
button({
style: styles.button,
children: "Click me"
})
]
});
```
--------------------------------
### Get Current Nuvemshop SDK State
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/state
Demonstrates how to retrieve the current application state using the `getState` function from the Nuvemshop SDK. This is useful for accessing initial application data and configurations.
```typescript
import { NubeSDK, NubeSDKState } from '@tiendanube/nube-sdk-types';
export function App(nube: NubeSDK) {
// Get current state
const currentState: Readonly = nube.getState();
// Access state properties
const cartTotal = currentState.cart.total;
const storeCurrency = currentState.store.currency;
const currentPage = currentState.location.pageType;
}
```
--------------------------------
### Implement Select Dropdown with JSX
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/components/select
Demonstrates how to use the Select component from the Nuvemshop SDK (nube-sdk-jsx) to create a dropdown input. It shows how to define options, set an initial value, and handle the onChange event.
```jsx
import { Box, Select } from "@tiendanube/nube-sdk-jsx";
function MyComponent() {
return (
);
}
```
--------------------------------
### Styled Components with Keyframes Animation (Function Call)
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Demonstrates defining and using CSS keyframe animations with the `keyframes` function and applying them to components via the `styled()` function. Includes 'pulse' and 'slideIn' animations, rendered using function calls.
```javascript
import { styled, keyframes } from "@tiendanube/nube-sdk-ui";
import { box } from "@tiendanube/nube-sdk-ui";
const pulse = keyframes`
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.1);
opacity: 0.8;
}
100% {
transform: scale(1);
opacity: 1;
}
`;
const slideIn = keyframes`
from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
`;
const AnimatedBox = styled(box)`
animation: ${pulse} 2s ease-in-out infinite;
`;
const SlideInBox = styled(box)`
animation: ${slideIn} 0.5s ease-out;
`;
AnimatedBox({
children: "Pulsing content"
});
SlideInBox({
children: "Sliding content"
});
```
--------------------------------
### Combine StyleSheet and styled() for Styling
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Demonstrates how to combine reusable styles created with `StyleSheet.create` and dynamic styles applied using the `styled()` function for different styling needs.
```javascript
// Reusable styles with StyleSheet
const baseStyles = StyleSheet.create({
card: {
backgroundColor: theme.color.main.background,
borderRadius: theme.border.radius,
padding: "16px",
},
});
// Static styles with styled()
const HighlightCard = styled(box)`
background-color: ${theme.color.accent};
border: 2px solid ${theme.border.color};
`;
```
--------------------------------
### Get Item from Async Session Storage
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/browser-apis
Illustrates how to retrieve a stored value using the `getItem` method from `asyncSessionStorage`. This allows applications to access data persisted in the browser's session storage from within a web worker.
```TypeScript
import type { NubeSDK } from "@tiendanube/nube-sdk-types";
export function App(nube: NubeSDK) {
const browser = nube.getBrowserAPIs();
browser.asyncSessionStorage.getItem("my_custom_field").then((value) => {
console.log("my_custom_field", value);
});
}
```
--------------------------------
### Integrate Stylesheet with Theme Tokens
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Shows how to seamlessly integrate `StyleSheet` with the theme system, using theme tokens for consistent design across components.
```javascript
import { StyleSheet, theme } from "@tiendanube/nube-sdk-ui";
const styles = StyleSheet.create({
primaryButton: {
backgroundColor: theme.color.accent,
color: theme.color.main.foreground,
padding: "12px 24px",
borderRadius: theme.border.radius,
},
card: {
backgroundColor: theme.color.main.background,
border: `1px solid ${theme.border.color}`,
borderRadius: theme.box.border.radius,
padding: "16px",
},
});
```
--------------------------------
### Validate Cart Content
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/events
This snippet illustrates how to use `cart:validate` to signal cart validity. It requires `has_cart_validation` to be true in the script configuration. The example shows how to reject the cart if it has fewer than 5 items and send a success status otherwise.
```javascript
// Tell NubeSDK that this script wants to validate the content of the cart
nube.send("config:set", () => ({
config: {
has_cart_validation: true
},
}));
nube.on("cart:update", ({ cart }) => {
// Reject the cart if it has fewer than 5 items
if (cart.items.length < 5) {
// Dispatch a failed `cart:validate` event with the reason why it failed to validate
nube.send("cart:validate", () => ({
cart: {
validation: {
status: "fail",
reason: "Cart must have at least 5 items!",
},
},
}));
} else {
// Dispatch a successful `cart:validate` event
nube.send("cart:validate", () => ({
cart: {
validation: {
status: "success",
},
},
}));
}
}
```
--------------------------------
### Listen for Checkout Page Ready Events
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/events
This snippet demonstrates how to listen for the `checkout:ready` event, which is dispatched by the `checkout` component whenever a new checkout page is loaded or a page transition occurs. It allows for executing logic based on the current checkout page, such as the success page.
```typescript
import type { NubeSDK } from "@tiendanube/nube-sdk-types";
export function App(nube: NubeSDK) {
nube.on("checkout:ready", ({ location }) => {
// Trigger logic every time the user navigates to a new checkout page
const { page } = location;
// You can inspect the current page using:
console.log("Current page:", page);
// Example: Only run logic on the success page
if (page.type === "checkout" && page.data.step === "success") {
// Your custom behavior here
}
});
}
```
--------------------------------
### Styled Components with Keyframes Animation (JSX)
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Shows how to define and use CSS keyframe animations with the `keyframes` function and apply them to components using the `styled()` function. Includes 'pulse' and 'slideIn' animations, rendered using JSX.
```javascript
import { styled, keyframes } from "@tiendanube/nube-sdk-ui";
import { Box } from "@tiendanube/nube-sdk-jsx";
const pulse = keyframes`
0% {
transform: scale(1);
opacity: 1;
}
50% {
transform: scale(1.1);
opacity: 0.8;
}
100% {
transform: scale(1);
opacity: 1;
}
`;
const slideIn = keyframes`
from {
transform: translateX(-100%);
opacity: 0;
}
to {
transform: translateX(0);
opacity: 1;
}
`;
const AnimatedBox = styled(Box)`
animation: ${pulse} 2s ease-in-out infinite;
`;
const SlideInBox = styled(Box)`
animation: ${slideIn} 0.5s ease-out;
`;
Pulsing contentSliding content
```
--------------------------------
### Escutar evento coupon:add:success
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/events
Registra um listener para o evento `coupon:add:success`, que é disparado quando um cupom é adicionado com sucesso ao carrinho. O listener recebe os dados do cupom aplicado.
```javascript
nube.on("coupon:add:success", ({ coupon }) => {
console.log(`Coupon ${coupon.code} was successfully applied`);
});
```
--------------------------------
### Main Script Entry Point - TypeScript
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/script-structure
Defines the main entry point for a Nuvemshop SDK script. The exported 'App' function receives the NubeSDK object for interacting with the SDK.
```TypeScript
import type { NubeSDK } from "@tiendanube/nube-sdk-types";
export function App(nube: NubeSDK) {
// your code goes here
}
```
--------------------------------
### Use Theme Tokens vs. Hardcoded Values
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Illustrates the best practice of using theme tokens for styling to maintain consistency across the application, contrasting it with the avoidance of hardcoded values.
```javascript
// ✅ Good - uses theme tokens
const styles = StyleSheet.create({
button: {
backgroundColor: theme.color.accent,
borderRadius: theme.border.radius,
},
});
// ❌ Avoid - hardcoded values
const styles = StyleSheet.create({
button: {
backgroundColor: "#007bff",
borderRadius: "4px",
},
});
```
--------------------------------
### Compose Styled Components
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Demonstrates how to chain styled components to build more complex UI elements by inheriting and extending styles.
```javascript
const BaseStyledBox = styled(box)`
background-color: red;
padding: 16px;
`;
const FinalStyledBox = styled(BaseStyledBox)`
border: 2px solid black;
margin: 8px;
`;
```
--------------------------------
### Animate Component with Theme Tokens
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Combines keyframe animations with theme tokens for consistent and dynamic visual effects. Requires the `@tiendanube/nube-sdk-ui` package.
```javascript
import { styled, keyframes, theme } from "@tiendanube/nube-sdk-ui";
const glow = keyframes`
0% {
box-shadow: 0 0 5px ${theme.color.accent};
}
50% {
box-shadow: 0 0 20px ${theme.color.accent}, 0 0 30px ${theme.color.accent};
}
100% {
box-shadow: 0 0 5px ${theme.color.accent};
}
`;
const GlowingButton = styled(button)`
background-color: ${theme.color.accent};
color: white;
padding: 12px 24px;
border-radius: ${theme.border.radius};
animation: ${glow} 2s ease-in-out infinite;
`;
```
--------------------------------
### Enviar evento customer:update
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/events
Envia o evento `shipping:select` (nota: este parece ser um erro na documentação original, deveria ser `customer:update`) para atualizar os dados do cliente no checkout. O exemplo envia dados de frete.
```javascript
nube.send("shipping:select", () => ({
shipping: {
selected: "OPTION_ID",
}
}));
```
--------------------------------
### Apply Theme Color Opacity
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Shows how to create transparent versions of theme colors using predefined opacity values. This is useful for creating overlays or subtle background effects.
```javascript
import { theme } from "@tiendanube/nube-sdk-ui";
const styles = StyleSheet.create({
overlay: {
backgroundColor: theme.color.accent.opacity(50), // 50% opacity
},
subtle: {
backgroundColor: theme.color.main.background.opacity(10), // 10% opacity
},
transparent: {
backgroundColor: theme.color.accent.opacity(0), // 0% opacity
},
});
```
--------------------------------
### Escutar evento shipping:update
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/events
Registra um listener para o evento `shipping:update`, disparado quando o método de frete é alterado no checkout. O listener recebe os dados de frete, incluindo a opção selecionada.
```javascript
nube.on("shipping:update", ({ shipping }) => {
if (shipping?.selected) {
console.log(`Shipping method selected has changed to: ${shipping?.selected}`);
}
});
```
--------------------------------
### Enviar e escutar evento shipping:select
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/events
Envia o evento `shipping:select` para alterar a opção de frete no checkout e registra listeners para os eventos de sucesso (`shipping:select:success`) e falha (`shipping:select:fail`).
```javascript
function App (nube: NubeSDK) {
nube.send("shipping:select", () => ({
shipping: {
selected: "OPTION_ID",
}
}));
nube.on("shipping:select:success", ({ shipping }) => {
console.log("selected option", shipping.selected)
});
nube.on("shipping:select:fail", ({ shipping }) => {
console.log("selected option", shipping.selected)
});
}
```
--------------------------------
### Apply Theme Colors in Stylesheet
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Demonstrates how to use theme colors from the NubeSDK UI to style components, ensuring they adapt to the store's theme. This involves importing the theme object and accessing color properties.
```javascript
import { theme } from "@tiendanube/nube-sdk-ui";
const styles = StyleSheet.create({
adaptiveButton: {
backgroundColor: theme.color.accent,
color: theme.color.main.foreground,
},
});
```
--------------------------------
### Basic Styled Box Component (Function Call)
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Illustrates the basic usage of the `styled()` function to create a custom styled Box component using function call syntax. It applies a red background, padding, and border-radius.
```javascript
import { styled } from "@tiendanube/nube-sdk-ui";
import { box } from "@tiendanube/nube-sdk-ui";
const StyledBox = styled(box)`
background-color: red;
padding: 16px;
border-radius: 8px;
`;
StyledBox({
children: "Custom styled content"
});
```
--------------------------------
### Basic Styled Box Component (JSX)
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/styling
Demonstrates the basic usage of the `styled()` function to create a custom styled Box component using JSX syntax. It applies a red background, padding, and border-radius.
```javascript
import { styled } from "@tiendanube/nube-sdk-ui";
import { Box } from "@tiendanube/nube-sdk-jsx";
const StyledBox = styled(Box)`
background-color: red;
padding: 16px;
border-radius: 8px;
`;
Custom styled content
```
--------------------------------
### Configurar conteúdo de slot UI com componente JSX
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/events
Utiliza `nube.send('ui:slot:set')` para definir o conteúdo de um slot de UI com um componente React (JSX). O exemplo mostra como renderizar um componente `Row` com texto.
```javascript
import type { NubeSDK } from "@tiendanube/nube-sdk-types";
import { Row, Txt } from "@tiendanube/nube-sdk-jsx";
function MyComponent() {
return (
Hello!
);
}
export function App(nube: NubeSDK) {
nube.send("ui:slot:set", () => ({
ui: {
slots: {
after_line_items: ,
},
},
}));
}
```
--------------------------------
### Escutar evento coupon:add:fail
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/events
Registra um listener para o evento `coupon:add:fail`, que é disparado quando ocorre uma falha ao adicionar um cupom ao carrinho. O listener recebe os dados do cupom que falhou.
```javascript
nube.on("coupon:add:fail", ({ coupon }) => {
console.log(`Failed to apply coupon ${coupon.code}`);
});
```
--------------------------------
### Escutar evento payment:update
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/events
Registra um listener para o evento `payment:update`, disparado quando o método de pagamento é alterado no checkout. O listener recebe os dados do pagamento, incluindo o método selecionado.
```javascript
nube.on("payment:update", ({ payment }) => {
console.log(`payment method has changed to: ${payment?.selected}`);
});
```
--------------------------------
### Using the Field Component
Source: https://dev.nuvemshop.com.br/es/docs/applications/nube-sdk/components/field
Demonstrates how to import and use the Field component from the '@tiendanube/nube-sdk-jsx' library. It shows the basic props like name, label, and event handlers.
```jsx
import { Field } from "@tiendanube/nube-sdk-jsx";
{}}
onBlur={() => {}}
onFocus={() => {}}
/>;
```