vivek modi
vivek modi

Reputation: 53

Not able to aply font weight in react

I am trying to give font weight to my span as inline css.

interface Label {
    title: string;
    fontSize: string;
    fontColor: string;
    fontFamily: string;
    fontWeight: string;
}
const Label = (props:Label) => {
    return (
        <span style={{color:props.fontColor,fontSize:props.fontSize,fontFamily:props.fontFamily,fontWeight:props.fontWeight}}>{props.title}</span>
    )
}

It's giving me Type 'string' is not assignable to type 'FontWeight. I am calling this component like

<Label title="SYNOASSESS" fontSize="30.1638px"  fontFamily="Futura" fontColor="#2789FC" fontWeight="bold" />

If i write

<span style={{color:props.fontColor,fontSize:props.fontSize,fontFamily:props.fontFamily,fontWeight:"bold"}}>{props.title}</span>

Then it's working fine but fontWeight is not working with props.

Upvotes: 1

Views: 1891

Answers (3)

Nadeeshani William
Nadeeshani William

Reputation: 808

TS doesn't know more than fontWeight is a string. So need to do type casting.

interface LabelProps {
  title: string;
  fontSize: string;
  fontColor: string;
  fontFamily: string;
  fontWeight: string;
}

const Label = (props: LabelProps) => {
  const boldText = {
    fontWeight: props.fontWeight
  } as React.CSSProperties;

  return (
    <span
      style={{
        color: props.fontColor,
        fontSize: props.fontSize,
        fontFamily: props.fontFamily,
        fontWeight: boldText.fontWeight
      }}
    >
       {props.title}
    </span>
  );

sandbox

or you can wrap entire style object with React.CSSProperties.

const styles = {
  color:props.fontColor,
  fontSize:props.fontSize,
  fontFamily:props.fontFamily,
  fontWeight:props.fontWeight
 } as React.CSSProperties;`

Upvotes: 1

Edgar
Edgar

Reputation: 91

One way of doing it is to use this:

const styles = {color:props.fontColor,fontSize:props.fontSize,
fontFamily:props.fontFamily,fontWeight:props.fontWeight} as React.CSSProperties;

and then:

<span style={styles}>{props.title}</span>

Upvotes: 0

Neel Dsouza
Neel Dsouza

Reputation: 1549

Typescript doesn't understand 'fontWeigth'. You can look this issue to understand more. Can u try below code

import React from "react";
import { render } from "react-dom";

interface Label {
    title: string;
    fontSize: string;
    fontColor: string;
    fontFamily: string;
    'font-weight': string;
}
const Label = (props:Label) => {
    return (
        <span style={{color:props.fontColor,fontSize:props.fontSize,fontFamily:props.fontFamily,fontWeight:props['font-weight']}}>{props.title}</span>
    )
}
function App() {
  return (
      <div className="App">
        <Label title="SYNOASSESS" fontSize="30.1638px"  fontFamily="Futura" fontColor="#2789FC" font-weight="bold" />
      </div>
  );
}

const rootElement = document.getElementById("root");
render(<App />, rootElement);

Upvotes: 0

Related Questions