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.
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.
interface MyComponentProps {
text: string
}
const MyComponent = (prop: MyComponentProps) => {
return <div>{prop.text}</div>
}
Then I can call the above component like:
<MyComponent text="Some text" />
Below is another way. Here I destruct the props and use only the prop I am interested in.
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.
const MyComponent = (props: {text: string}) => {
return <div>{prop.text}</div>
}