How to pass a string literal as a single prop in React Typescript

Last updated : Jul 30, 2023 12:00 AM

To pass a string literal as a single prop in a React component using TypeScript, I must define a prop type for the component that accepts a string literal.

Take a look at the below example.

Simple componentDescription
const MyComponent = (text: string) => { 
   return <div>{text}</div> 
}

The MyComponent as is cannot be used in another component. To use the MyComponent in another component, I must first change the MyComponent definition. The MuComponent's props need a type. Below are two ways to achieve that.

1. Using a TypeScript interface for the prop type

Here I use an interface to define the prop type. My component prop is explicitly type-casted to this interface.

TypeScript interfaceDescription
interface MyComponentProps { 
   text: string 
}
const MyComponent = (prop: MyComponentProps) => { 
   return <div>{prop.text}</div> 
}

Then I can call the above component like:

Simple component usageDescription
<MyComponent text="Some text" />

Below is another way. Here I destruct the props and use only the prop I am interested in.

Destructed propsDescription
interface MyComponentProps { 
   text: string 
}
const MyComponent = ({ text }: MyComponentProps) => { 
   return <div>{text}</div> 
}

2. Using an inline TypeScript interface for the prop type

Here I use an inline interface to define the prop type.

Inline TypeScript interfaceDescription
const MyComponent = (props: {text: string}) => { 
   return <div>{prop.text}</div> 
}
Lance

By: Lance

Hi, I'm Lance Raney, a dedicated Fullstack Developer based in Oklahoma with over 15 years of exp

Read more...