Shawkry
Shawkry

Reputation: 11

How to dynamically style a button's background color using vanilla-extract and TypeScript

such as:

button.tsx:

import {buttonStyle} from './buttuon.css.ts'
const Button = ({backgroundColor}) => {
  return (
    <button className={buttonStyle}>button<button/>
  )
}

button.css.ts:

import { style } from '@vanilla-extract/css';
export const buttonStyle = style({
    width: '100%',
    backgroundColor: ?
});

I tried to write it this way, but it didn't solve the problem.

button.tsx:

import {buttonStyle} from './buttuon.css.ts'
const Button = ({backgroundColor}) => {
  return (
    <button className={buttonStyle(backgroundColor)}>button<button/>
  )
}

button.css.ts:

import { style } from '@vanilla-extract/css';
export const buttonStyle = (backgroundColor) => style({
    width: '100%',
    backgroundColor: backgroundColor
});

error info: storybook: You can only export plain objects, arrays, strings, numbers and null/undefined.null/undefined. storybook: Plugin: vanilla-extract

Upvotes: 1

Views: 29

Answers (1)

SELA
SELA

Reputation: 6878

In order to dynamically style a HTML element background color using vanilla-extract, you'll need to use its built-in mechanism for creating dynamic styles, such as createVar and vars. import if from @vanilla-extract/css.

Refer the code below for reference:

import { style, createVar } from '@vanilla-extract/css';

export const backgroundColorVar = createVar(); // Create varible to hold background color

export const buttonStyle = style({
  width: '100%',
  backgroundColor: backgroundColorVar, // Set value here
});

In your button.tsx refer it like below:

import {buttonStyle, backgroundColorVar} from './button.css';

<button className = {buttonStyle} style = {{ [backgroundColorVar]: backgroundColor}}> Button </button>

Upvotes: 1

Related Questions