Colorful Codes
Colorful Codes

Reputation: 597

How do I correctly style a component in fluent UI/React/ts?

I am trying to add a background color to this div:

import * as React from 'react'
import { Itest } from '../../../../../models'
import { getPreviewStyles } from './preview.style.ts'

type IPreviewProps = Itest

const PreviewC: React.FunctionComponent<IPreviewProps> = (props: IPreviewProps) => {
  console.log(props)
  return (
    <div>
      <h1 className="base">test test</h1>
      <p>testing testing</p>
      <img src="workingAtComputer.jpg"></img>
    </div>
  )
}

export const Preview = PreviewC

Here I am trying to add a background color of purple:

import { IStyle } from 'office-ui-fabric-react'

export interface IPreviewStyles {
  base: IStyle
}

export const getPreviewStyles = (): IPreviewStyles => {
  return {
    base: {
      backgroundColor: 'purple',
    }
}

I get this error in the first file: "'getPreviewStyles' is declared but its value is never read." How can I have the styling applied to the div with className "base"? Please assist. Thanks.

Upvotes: 0

Views: 3770

Answers (1)

Marko Savic
Marko Savic

Reputation: 2384

You probably want to implement css-in-js but for that you need to use Merge styles which comes along side with Office Fabric UI or FluentUI as newer version.

Preview.style.ts:


import { mergeStyleSets } from '@fluentui/merge-styles';

export interface IPreviewStyles {
  base: string;
}

export const getPreviewStyles = (): IPreviewStyles => {
  return mergeStyleSets({
    base: {
      background: 'purple',
    },
  });
};

Component:

import * as React from 'react'
import { Itest } from '../../../../../models'
import { getPreviewStyles } from './preview.style.ts'

type IPreviewProps = Itest

const PreviewC: React.FunctionComponent<IPreviewProps> = (props: IPreviewProps) => {

  const { base } = getPreviewStyles()

  return (
    <div>
      <h1 className={base}>test test</h1>
      <p>testing testing</p>
      <img src="workingAtComputer.jpg"></img>
    </div>
  )
}

export const Preview = PreviewC

You can read more about Merge styles API here. And my recommendation for you is to switch on latest version of FluentUI.

Upvotes: 1

Related Questions